Sunday, February 17, 2013

SQL SERVER TOP CLAUSE

SQL SERVER TOP CLAUSE   returns rows by number, percentage.

for ex:  select top 3 highest paid employees in emp table

select  top 3 * from emp;

EMPNO    ENAME    JOB    MGR    HIREDATE    SAL    COMM    DEPTNO
7839    KING    PRESIDENT    NULL    1981-11-17    5000.00    NULL    10
7902    FORD    ANALYST    7566    1981-12-03    3000.00    NULL    20
7566    JONES    MANAGER    7839    1981-04-02    2975.00    300.00    20


EMP TABLE

EMPNOENAMEJOBMGRHIREDATESALCOMMDEPTNO
7369SMITHCLERK790212/17/1980 12:00:00 AM800.00
20
7499ALLENSALESMAN76982/20/1981 12:00:00 AM1600.00300.0030
7521WARDSALESMAN76982/22/1981 12:00:00 AM1250.00500.0030
7566JONESMANAGER78394/2/1981 12:00:00 AM2975.00
20
7654MARTINSALESMAN76989/28/1981 12:00:00 AM1250.001400.0030
7698BLAKEMANAGER78395/1/1981 12:00:00 AM2850.00
30
7782CLARKMANAGER78396/9/1981 12:00:00 AM2450.00
10
7839KINGPRESIDENT
11/17/1981 12:00:00 AM5000.00
10
7844TURNERSALESMAN76989/8/1981 12:00:00 AM1500.000.0030
7900JAMESCLERK769812/3/1981 12:00:00 AM950.00
30
7902FORDANALYST756612/3/1981 12:00:00 AM3000.00
20
7934MILLERCLERK77821/23/1982 12:00:00 AM1300.00
10

Ex:  Get top 5 Maximum sold products (from northwind)

select top 5 p.productid,od.productid,ProductName,od.[Total Price] from products p
join
(
select productid,Quantity*unitprice [Total Price] from [order details]
) od
on p.productid=od.productid
order by [Total Price] desc

O/P:
productid    productid    ProductName    Total Price
38    38    Côte de Blaye    15810.00
38    38    Côte de Blaye    15810.00
38    38    Côte de Blaye    10540.00
38    38    Côte de Blaye    10540.00
38    38    Côte de Blaye    10540.00


Ex:get top 3 shipped countries

select top 3 shipcountry,count(*) shipped from orders group by shipcountry
order by shipped desc
                             OR
select top 3  *
from (select shipcountry,count(*) shipped from orders group by shipcountry) o
order by shipped desc

shipcountry    shipped
USA    122
Germany    122
Brazil    83


Ex: get 5 percentage of orders placed in year 1996(northwind DB)

select top 5 percent  * from orders
where DATEPART(year,ShippedDate)=1996

User will get 8 rows, out of 143 rows   5%of 143 = 7.15 it will be ceiled ,so you will get 8 records

Tags:SQL SERVER TOP CLAUSE,using TOP CLUASE in T-SQL, using TOP number,using TOP percent in SQL-SERVER

No comments:

Post a Comment