我正在尝试提取一个非常简单的报告,以查看前一天的数据。看起来类似于:
SELECT Name, Date, Count
FROM dbo.X
WHERE Date BETWEEN DATEADD(DD, -1, GETDATE()) AND DATEADD(DD, 0, GETDATE())
这很好,但是我被要求提供一列以显示前一天的数量,以供比较。我不确定如何执行此操作,因为datetime条件已经指定了最后一天。有没有一种方法可以使这项工作使选择列表看起来像这样?
SELECT Name, Date, YesterdaysCount, Count
编辑:示例数据:
Name Date Count
a 6/22/2020 1
b 6/22/2020 2
c 6/22/2020 3
d 6/22/2020 4
e 6/22/2020 5
a 6/21/2020 2
b 6/21/2020 4
c 6/21/2020 6
d 6/21/2020 8
e 6/21/2020 10
所需结果:
Name Date YesterdayCount Count
a 6/22/2020 2 1
b 6/22/2020 4 2
c 6/22/2020 6 3
d 6/22/2020 8 4
e 6/22/2020 10 5
答案 0 :(得分:1)
如果您没有时间组件,这应该可以工作。如果这样做的话,只需将“ Y. [Date] =”更改为与第一部分相同的内容即可。
SELECT [Name], [Date], [Count],
(SELECT SUM(Y.[Count]) FROM dbo.X AS Y WHERE Y.[Name] = X.[Name] AND Y.[Date] = DATEADD(DAY, -1, X.[DATE]) AS YesterdaysCount
FROM dbo.X
WHERE [Date] BETWEEN DATEADD(DD,-1,GETDATE()) AND DATEADD(DD, 0, GETDATE())
答案 1 :(得分:0)
有很多方法可以做到这一点,这是两种方法。 我建议每天使用变量 如果您只关心日期,我建议您使用日期而不是日期时间,这样可以加快搜索速度(包括变量和投射日期字段)
declare @table1 table (name varchar(10), YourDate datetime, YourCount int )
insert into @table1 values ('name1', '2020-06-19', 1)
--insert into @table1 values ('name1', '2020-06-20', 1)
insert into @table1 values ('name1', '2020-06-21', 2)
insert into @table1 values ('name1', '2020-06-22', 3)
insert into @table1 values ('name1', '2020-06-23', 4)
insert into @table1 values ('name1', '2020-06-24', 5)
--use date fiels for faster comparisson
declare @Today date=getdate(), @Yesterday date=dateadd(day,-1,getdate())
--using a left join to the same table for yesterdays (check for nulls)
SELECT t1.Name, t1.YourDate,
sum(isnull(t2.YourCount,0)) as YesterdayCount,
sum(isnull(t1.YourCount,0)) as TodayCount
From @table1 t1
Left Join @table1 t2 on t1.name=t2.name and t2.YourDate=cast(dateadd(day,-1,t1.YourDate) as date)
Where cast(t1.YourDate as date) BETWEEN @Yesterday AND @Today
Group By t1.name, t1.YourDate
--using outer apply
SELECT t1.Name, t1.YourDate,
sum(isnull(t2.YourCount,0)) as YesterdayCount,
sum(isnull(t1.YourCount,0)) as TodayCount
From @table1 t1
outer apply(
Select t3.YourCount From @table1 t3 where t3.YourDate=cast(dateadd(day,-1,t1.YourDate) as date)
) as t2
Where cast(t1.YourDate as date) BETWEEN @Yesterday AND @Today
Group By t1.name, t1.YourDate
答案 2 :(得分:-1)
SELECT
Name, Date,
(SELECT Count
WHERE Date BETWEEN DATEADD(DD, -2, GETDATE()) AND DATEADD(DD, -1, GETDATE())) AS YesterdaysCount, Count
FROM
dbo.X
WHERE
Date BETWEEN DATEADD(DD, -1, GETDATE()) AND DATEADD(DD, 0, GETDATE())