SQL Server:查询按列分组的DENSE_RANK()?

时间:2013-05-09 19:33:16

标签: sql-server

需要帮助在orders表上为此场景构建一个SQL语句,该表包含orderID, customerID, itemID和其他misc。列。

说表如下:

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

1 个答案:

答案 0 :(得分:7)

您可以使用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 |
相关问题