10.5.13

Ntile feature in SQL Server


I got a peculiar query from one of the user to fetch data from the tables.

 Here is the query, He needs to fetch 50% bottom data to the top and 50% top data to the bottom  of the table.      

  I've used Ntile option to manipulate the desired output.


create table #t(col1 varchar(6),col2 varchar(6))
--drop table #t
insert into #t values('a','s')
insert into #t values('a','g')
insert into #t values('b','h')
insert into #t values('b','r')
insert into #t values('s','j')
insert into #t values('s','k')
insert into #t values('e','o')
insert into #t values('e','p')
insert into #t values('q','x')
insert into #t values('q','c')
select * from #t

Select col1,col2 From (
    Select NTILE(2) Over (Order by col1 Desc) as HalfNumber, *
    From #t) as NtileTable
where HalfNumber = 1
union all
Select col1,col2 From (
    Select NTILE(2) Over (Order by col1 Desc) as HalfNumber, *
    From #t) as NtileTable
where HalfNumber = 2

Cheers,


Venkatesan Prabu .J
Head, KaaShiv InfoTech
A very best Inplant Training and Internship Providers in Chennai

1 comment:

  1. This is great blog for learning about the SQL Server.The interested candidate can improve their ability to join this company...
    Online Tutorial For SQL

    ReplyDelete