SQL Server 按过去 24 小时、上周和上个月对促销进行分组,并按周降序排序
Posted
技术标签:
【中文标题】SQL Server 按过去 24 小时、上周和上个月对促销进行分组,并按周降序排序【英文标题】:SQL Server Group a promotion by last 24 hours, last week and last month and sort by week descending 【发布时间】:2020-07-25 12:52:12 【问题描述】:我正在尝试查看过去 24 小时、一周和一个月内不同促销活动的成功率。为了获得过去 24 小时的促销金额,我使用了此代码,但我不明白如何获得上周和上个月的另外两列。然后最后我想按上周的数量降序订购。我希望能够在本月的任何时候运行此查询。请帮帮我。
SELECT Promotion
, Sum(Amount) AS Last_24
FROM dbo.CustomerPayment
WHERE Started >= DATEADD(day, - 1, GETDATE())
GROUP
BY Promotion
【问题讨论】:
样本数据,所需的输出将确保输出是您想要的。 【参考方案1】:您可以在单个查询中完成:
SELECT Promotion
, Sum(CASE WHEN Started >= DATEADD(day, -1, GETDATE()) THEN Amount ELSE 0 END) AS Last_24
, Sum(CASE WHEN Started >= DATEADD(day, -7, GETDATE()) THEN Amount ELSE 0 END) AS Last_Week
, Sum(Amount) AS Last_Month
FROM dbo.CustomerPayment
WHERE Started >= DATEADD(day, - 31, GETDATE())
GROUP
BY Promotion
ORDER BY Last_Week DESC
注意这部分:
WHERE Started >= DATEADD(day, - 31, GETDATE())
请按照您对“上个月”概念的解释进行澄清。
【讨论】:
【参考方案2】:使用条件聚合——即将条件移动到select
:
SELECT Promotion,
SUM(case when Started >= DATEADD(day, - 1, GETDATE()) then Amount end) AS Last_1_day,
SUM(case when Started >= DATEADD(day, - 7, GETDATE()) then Amount end) AS Last_7_day,
. . .
FROM dbo.CustomerPayment
GROUP BY Promotion;
不过,一个可能的问题。 GETDATE()
——尽管它的名字——返回一个时间分量到日期。我怀疑您实际上可能希望将其视为 date,而不是 datetime:
SELECT Promotion,
SUM(case when Started >= DATEADD(day, - 1, CONVERT(DATE, GETDATE())) then Amount end) AS Last_1_day,
SUM(case when Started >= DATEADD(day, - 7, CONVERT(DATE, GETDATE())) then Amount end) AS Last_7_day,
. . .
FROM dbo.CustomerPayment
GROUP BY Promotion;
【讨论】:
【参考方案3】:我正在寻找月/周。不是 7 / 30 天。
如果您愿意,只需使用变量来使该查询可读。
declare @monthstart date,
@weekstart date
;
select @monthstart=datefromparts(year(current_timestamp),month(current_timestamp),1)
select cast(DATEADD(d,1-DATEPART(WEEKDAY,current_timestamp),CURRENT_TIMESTAMP) as date) as Sunday,
cast(DATEADD(d,2-case when DATEPART(WEEKDAY,current_timestamp)=1 then 8 else DATEPART(WEEKDAY,current_timestamp) end,CURRENT_TIMESTAMP) as date) as Monday
;
【讨论】:
以上是关于SQL Server 按过去 24 小时、上周和上个月对促销进行分组,并按周降序排序的主要内容,如果未能解决你的问题,请参考以下文章