2013-05-09 84 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