Sql 2005 the ranking functions

468 views
401 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
468
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Sql 2005 the ranking functions

  1. 1. SQL 2005 - The ranking functions
  2. 2. The ranking functions – Step 1 USE tempdb; GO IF OBJECT_ID('dbo.Orders') IS NOT NULL DROP TABLE dbo.Orders; GO
  3. 3. The ranking functions – Step 2 CREATE TABLE dbo.Orders ( orderid INT NOT NULL, orderdate DATETIME NOT NULL, empid INT NOT NULL, custid VARCHAR(5) NOT NULL, qty INT NOT NULL, CONSTRAINT PK_Orders PRIMARY KEY NONCLUSTERED(orderid) );
  4. 4. The ranking functions – Step 3 CREATE UNIQUE CLUSTERED INDEX idx_UC_orderdate_orderid ON dbo.Orders(orderdate, orderid);
  5. 5. The ranking functions – Step 4 SET NOCOUNT ON; INSERT INTO dbo.Orders(orderid, orderdate, empid, custid, qty) VALUES(30001, '20030802', 3, 'B', 10); INSERT INTO dbo.Orders(orderid, orderdate, empid, custid, qty) VALUES(10001, '20031224', 1, 'C', 10); INSERT INTO dbo.Orders(orderid, orderdate, empid, custid, qty) VALUES(10005, '20031224', 1, 'A', 30); INSERT INTO dbo.Orders(orderid, orderdate, empid, custid, qty) VALUES(40001, '20040109', 4, 'A', 40); INSERT INTO dbo.Orders(orderid, orderdate, empid, custid, qty) VALUES(10006, '20040118', 1, 'C', 10);
  6. 6. The ranking functions – Step 5 -- Analytical Ranking Functions –- without PARTITION BY clause   SELECT orderid, qty,   ROW_NUMBER() OVER(ORDER BY qty) AS rownum,   RANK()       OVER(ORDER BY qty) AS rnk,   DENSE_RANK() OVER(ORDER BY qty) AS densernk,   NTILE(4)     OVER(ORDER BY qty) AS ntile4 FROM dbo.Orders ORDER BY qty; GO
  7. 7. The ranking function - Output Ordered Qty Rownum Rnk Densernk Ntile4 30001 10 1 1 1 1 10001 10 2 1 1 1 10006 10 3 1 1 2 10005 30 4 4 2 3 40001 40 5 5 3 4

×