假设我有一个包含以下列的表:
我现在想看到这个结果:
Sold in the last 7 days | Sold in last 14 days
-----------------------------------------------------
10 | 20
我可以使用where子句在之间使用,但是如何在7天和14天内获得售出的数量?
答案 0 :(得分:3)
在WHERE子句中过滤以获取第0天到第14天。然后分别在第0天到第7天汇总。
SELECT
...,
SUM(CASE WHEN SaleDate >= DATEADD(day, -7, GETDATE()) THEN 1 ELSE 0 END) AS 7days,
COUNT(*) AS 14days
FROM
MyTable
WHERE
SaleDate >= DATEADD(day, -14, GETDATE())
GROUP BY
...
答案 1 :(得分:0)
select sum(Qty), datediff(w, getdate(), SaleDate) as Period
from table
group by datediff(ww, getdate(), SaleDate)
答案 2 :(得分:0)
在MS T-SQL 2003中测试
declare @whatever table(
qty int,
saledate datetime
)
insert into @whatever select 1, getdate()
insert into @whatever select 2, dateadd(dd, -1, getdate())
insert into @whatever select 2, dateadd(dd, -2, getdate())
insert into @whatever select 1, dateadd(dd, -3, getdate())
insert into @whatever select 1, dateadd(dd, -4, getdate())
insert into @whatever select 1, dateadd(dd, -5, getdate())
insert into @whatever select 1, dateadd(dd, -6, getdate())
insert into @whatever select 1, dateadd(dd, -7, getdate())
insert into @whatever select 1, dateadd(dd, -8, getdate())
insert into @whatever select 1, dateadd(dd, -9, getdate())
insert into @whatever select 2, dateadd(dd, -10, getdate())
insert into @whatever select 2, dateadd(dd, -11, getdate())
insert into @whatever select 1, dateadd(dd, -15, getdate())
insert into @whatever select 2, dateadd(dd, -16, getdate())
select
qty,
sum(
case
when datediff(dd, saledate, getdate()) between 0 and 7 then 1
else 0
end
) as [Sold in last 7 days],
sum(
case
when datediff(dd, saledate, getdate()) between 0 and 14 then 1
else 0
end
) as [Sold in last 14 days]
from
@whatever
group by
qty
;