我有一个查询,可以提取每个日期的订单数量。
SELECT
name, CONVERT(VARCHAR(10), order_date, 120) AS order_date,
COUNT(1) AS orders
FROM
orders AS od
WHERE
id = 73
GROUP BY
CONVERT(VARCHAR(10), order_date, 120), name
ORDER BY
order_date, name
以下是我运行查询时得到的结果:
name order_date orders
--------------------------
20pmam 2016-07-27 39
20pmam 2016-07-28 30
20pmam 2016-07-29 32
20pmam 2016-07-31 468
20pmam 2016-08-02 75
20pmam 2016-07-05 30
我需要我的结果是这样的,新的列日
name order_date orders day
-------------------------------
20pmam 2016-07-27 39 1
20pmam 2016-07-28 30 2 // days between 2016-07-27 to 2016-07-28
20pmam 2016-07-29 32 3 // days between 2016-07-27 to 2016-07-29
20pmam 2016-07-31 468 5 // days between 2016-07-27 to 2016-07-31
20pmam 2016-08-02 75 7 // days between 2016-07-27 to 2016-08-02
20pmam 2016-08-05 30 10 // days between 2016-07-27 to 2016-08-05
第一个/最小order_date应该被视为第1天(在上面的结果中2016-07-27是第1天)并且应该根据第一个/最小order_date计算其他。
这很容易吗?
我不知道如何获得理想的结果。我很感激任何建议。
答案 0 :(得分:2)
您可以执行此操作cross apply
以获取每个order_date之前的最短日期,并在datediff
中使用它。
SELECT name,CONVERT(VARCHAR(10), order_date, 120) AS order_date, Count(1) [orders],
1+coalesce(datediff(day,t.min_date,od.order_date),0) as [Day]
FROM orders AS od
cross apply (select min(od1.order_date) as min_date
from orders od1
where od.id=od1.id and od.name=od1.name and od1.order_date<od.order_date) t
WHERE id = 73
GROUP BY CONVERT(VARCHAR(10), order_date, 120),name,datediff(day,t.min_date,od.order_date)
ORDER BY order_date,name
答案 1 :(得分:2)
尝试类似:
SELECT name,
CONVERT(VARCHAR(10), order_date, 120) AS order_date,
Count(1) AS orders,
DATEDIFF(DAY, first_order_date, order_date) + 1
FROM orders AS od
JOIN (SELECT min(order_date) AS first_order_date
FROM orders) as fod ON 1 = 1
WHERE id = 73
GROUP BY CONVERT(VARCHAR(10), order_date, 120),
name,
DATEDIFF(DAY, first_order_date, order_date) + 1
ORDER BY order_date,
name
希望这能解决您的问题