计算项目在最近日期之间的差异

时间:2019-04-15 21:23:27

标签: sql sql-server

我希望计算每天装载的卡车之间的重量差。基本上,我想知道每天增加的重量。从理论上讲,卡车将每天运行,但是我在模拟数据库中使用的是简化的数据集。

这是我想出的代码:

--create table dbo.truck 
--(TruckID int, Weight float, datetrunc date, weightdiff float)
declare @dt1 datetime, @dt2 datetime
select @dt2 = max(datetrunc) from truck
select @dt1 = max(datetrunc) from truck where datetrunc < @dt2
select @dt1 [dt1], @dt2 [dt2]

SELECT t1.truckid, t2.weight - t1.weight [WeightDiff]
FROM truck t1
inner join truck t2 ON t1.truckid = t2.truckid
WHERE t1.datetrunc = @dt1
AND   t2.datetrunc = @dt2


UPDATE truck SET WeightDiff = x.WeightDiff
FROM (
SELECT t1.truckid, t2.weight - t1.weight [WeightDiff]
FROM truck t1
inner join truck t2 ON t1.truckid = t2.truckid
WHERE t1.datetrunc = @dt1
AND   t2.datetrunc = @dt2
) AS X
WHERE truck.datetrunc = @dt2
AND x.truckid = truck.truckid


SELECT t1.truckid,  @dt2,      t2.weight - t1.weight 
FROM truck t1
inner join truck t2 ON t1.truckid = t2.truckid
WHERE t1.datetrunc = @dt1
AND   t2.datetrunc = @dt2

我希望每个日期之间都能有所不同。但是,它只是显示最新日期之间的差异,同时删除并清空其他行:

TruckID Weight  datetrunc   weightdiff
1   1000    2019-03-01  NULL
2   1111    2019-03-01  NULL
3   1222    2019-03-01  NULL
1   1050    2019-03-15  NULL
2   1700    2019-03-15  NULL
3   1400    2019-03-15  NULL
1   1125    2019-03-31  75
2   1725    2019-03-31  25
3   1600    2019-03-31  200

我想要:

TruckID Weight  datetrunc   weightdiff
1   1000    2019-03-01  NULL
2   1111    2019-03-01  NULL
3   1222    2019-03-01  NULL
4   1400    2019-03-01  NULL
1   1050    2019-03-15  50
2   1700    2019-03-15  589
3   1400    2019-03-15  178
4   1490    2019-03-15  90
1   1125    2019-03-31  75
2   1725    2019-03-31  25
3   1600    2019-03-31  200
4   1900    2019-03-31  510

注意如何从我的数据集中删除一些TruckID 4。另外,它如何替代体重差异。

我似乎无法弄清楚如何正确显示数据。任何建议都会有所帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

对于SQL Server 2008

select a.truckid, a.weight, a.datetrunc, (a.weight - c.weight) weightdiff
from truck a
outer apply (select top 1 weight from truck b where b.datetrunc<a.datetrunc and b.truckid=a.truckid order by b.datetrunc desc) c

较新的SQL Server

select truckid, weight, datetrunc, weight - lag(weight) over (partition by truckid order by datetrunc) weightdiff
from truck