我正在尝试创建特定时间段内客户下达的订单总数(按日期排序)。
我尝试使用分区函数,但以下查询未产生正确的结果。任何帮助将不胜感激
select
CustomerID
, Order ID
, COUNT(OrderID) OVER (PARTITION BY CustomerID ORDER BY OrderDate) RunningOrderCount
from #existingtable
我希望结果是所有客户ID的表,所有他们相应的订单ID的表,然后是包含订单计数的字段,例如...
CustomerID OrderID OrderCount
1234 5675 1
1234 5676 2
1234 5677 3
1234 5678 4
1234 5679 5
答案 0 :(得分:2)
我认为您正在寻找的是ROW_NUMBER()
SELECT
CustomerID
, OrderID
, ROW_NUMBER() OVER (PARTITION BY CustomerID ORDER BY OrderDate) RunningOrderCount
from #existingtable
答案 1 :(得分:1)
此行将返回一年的计数
select
CustomerID
, Order ID
, count(*) OVER
(PARTITION BY CustomerID ORDER BY DATEPART(yy,orderDate) ) as year_total
from #customtable
使用row_number代替count(*)