2013-05-09 85 views
3

在需要幫助的情況下,通過orders表來構建此場景的SQL語句,該表包含orderID, customerID, itemID和其他misc。列。SQL Server:查詢DENSE_RANK()按列分組?

說表的樣子:

OrderID CustomerID ItemID Details 
1  1234  543 abc 
2  1234  643 xxx 
3  1234  743 try 
4  5678  743 try 
5  5678  999 iuy 
6  5678  643 xxx 

我想吃點什麼作爲附加列,一個計數器,每一個新的開始customerID時間增量,另一個遍歷計數項目客戶購買。我正在使用DENSE_RANK(),我可以做第一個計數器,但我該如何處理第二個計數器呢?

SELECT 
    DENSE_RANK() OVER (ORDER BY CustomerID) as Counter, 
    * 
FROM 
    Orders 
ORDER BY 
    CustomerID ASC 

這給了我:

Counter OrderID CustomerID ItemID Details 
1  1  1234  543 abc 
1  2  1234  643 xxx 
1  3  1234  743 try 
2  4  5678  743 try 
2  5  5678  999 iuy 
2  6  5678  643 xxx 

最後,我要的是Counter2列加莫名其妙:

Counter Counter2 OrderID CustomerID ItemID Details 
1  1  1  1234  543 abc 
1  2  2  1234  643 xxx 
1  3  3  1234  743 try 
2  1  4  5678  743 try 
2  2  5  5678  999 iuy 
2  3  6  5678  643 xxx 
+0

哦,我只是想通了: ROW_NUMBER()OVER(PARTITION BY客戶id ORDER BY項目ID)爲C2的 – 2013-05-09 19:36:11

回答

6

您可以使用row_number()獲得第二個計數器:

SELECT 
    DENSE_RANK() OVER (ORDER BY CustomerID) as Counter, 
    row_number() over(partition by customerId order by orderId) Counter2, 
    * 
FROM 
    Orders 
ORDER BY 
    CustomerID ASC; 

SQL Fiddle with Demo。其結果是:

| COUNTER | COUNTER2 | ORDERID | CUSTOMERID | ITEMID | DETAILS | 
---------------------------------------------------------------- 
|  1 |  1 |  1 |  1234 | 543 |  abc | 
|  1 |  2 |  2 |  1234 | 643 |  xxx | 
|  1 |  3 |  3 |  1234 | 743 |  try | 
|  2 |  1 |  4 |  5678 | 743 |  try | 
|  2 |  2 |  5 |  5678 | 999 |  iuy | 
|  2 |  3 |  6 |  5678 | 643 |  xxx | 
+0

正確的,我只是碰到了這個頁面,想通了這一點太:HTTP ://thehobt.blogspot.com/2009/02/rownumber-rank-and-denserank.html - 謝謝你! – 2013-05-09 19:37:16

+0

謝謝!這對我有效。 – David 2016-04-14 13:25:54