如何找到从 10 月 1 日至今的每一天的价格总和

Posted

技术标签:

【中文标题】如何找到从 10 月 1 日至今的每一天的价格总和【英文标题】:how to find the sum of price for each day from 1st oct to till date 【发布时间】:2021-02-06 11:41:40 【问题描述】:
SELECT count(*), sum(price) 
FROM Orders  
where creationDate > '2020-10-01' and creationDate < '2020-10-02'

此查询给出了 10 月 1 日的订单总数和价格总和。

我想要从 10 月 1 日到截止日期的每一天的结果。在特定日期有多少订单及其价格总和。

【问题讨论】:

使用GROUP BY查询 我如何将每一天(从 10 月 1 日)到今天传递到这个查询? 【参考方案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

如果你想要一个 running 计数和求和,那么使用窗口函数:

select convert(date, creationDate) creationDay, 
    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, 1, convert(date, getdate()))
group by convert(date, creationDate)
order by creationDay

【讨论】:

以上是关于如何找到从 10 月 1 日至今的每一天的价格总和的主要内容,如果未能解决你的问题,请参考以下文章