问题描述
SELECT count(*),sum(price)
FROM Orders
where creationDate > '2020-10-01' and creationDate < '2020-10-02'
此查询给出10月1日的订单总数和价格总和。
我想要从10月1日到耕种日期的每一天的结果。在特定的一天有多少订单及其价格的总和。
解决方法
使用group by
:
select convert(date,creationDate) creationDay,count(*) cnt,sum(price) total_price
from Orders
where creationDate >= '20201001' and creationDate < dateadd(day,1,convert(date,getdate()))
group by convert(date,creationDate)
order by creationDay
如果要运行计数和求和,请使用窗口函数:
select convert(date,sum(count(*)) over(order by convert(date,creationDate)) running_cnt,sum(sum(price)) over(order by convert(date,creationDate)) total_running_price
from Orders
where creationDate >= '20201001' and creationDate < dateadd(day,creationDate)
order by creationDay