需要帮助在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
答案 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 |