SQL 单元格值之间的差异(LAG 功能不起作用)
SQL difference between cell values (LAG function not working)
很遗憾,由于使用 SQL Server 2008,我无法使用 lag
功能。
我需要找出不同时间两个值之间基于机器的差异。
我有一个 table 这样的:
ID | Time | Value | Machine
------+-----------+---------+-----------
7 | 12:00 | 154400 | 20
6 | 12:00 | 77840 | 17
5 | 11:00 | 10480 | 11
4 | 11:00 | 13214 | 14
3 | 11:00 | 76340 | 17
2 | 11:00 | 15410 | 20
1 | 10:00 | 75000 | 17
我需要找出 id 1 和 3 之间的差异 (76340-75000 = 1340)。
之前尝试过这些:
select
t1.Machine, t1.[ID], t2.[ID], t1.Value, t2.Value,
t2.Value - t1.Value as difference
from
hava t1
cross apply
hava t2
where
t1.Machine = t2.Machine
and t1.ID <> t2.ID
and t1.Machine = 17
但它与 t1.id 相比整个 table。
我无法使用 lag
功能 - 非常感谢您的帮助。
WITH CTE(ID , Time, Value, Machine)AS
(
SELECT 7,'12:00',154400,20 UNION ALL
SELECT 6,'12:00',77840,17 UNION ALL
SELECT 5,'11:00',10480,11 UNION ALL
SELECT 4,'11:00',13214,14 UNION ALL
SELECT 3,'11:00',76340,17 UNION ALL
SELECT 2,'11:00',15410,20 UNION ALL
SELECT 1,'10:00',75000,17
),
CTE2 AS
(
SELECT C.ID,C.TIME,C.Value,C.Machine,
ROW_NUMBER()OVER(PARTITION BY C.MACHINE ORDER BY C.TIME ASC)XCOL
FROM CTE AS C
)
SELECT X.ID,X.Time,X.Value, X2.Value, X.Machine
FROM CTE2 AS X
LEFT JOIN CTE2 AS X2 ON X.Machine=X2.Machine AND X.XCOL=X2.XCOL-1
WHERE X.Machine=17
很遗憾,由于使用 SQL Server 2008,我无法使用 lag
功能。
我需要找出不同时间两个值之间基于机器的差异。
我有一个 table 这样的:
ID | Time | Value | Machine
------+-----------+---------+-----------
7 | 12:00 | 154400 | 20
6 | 12:00 | 77840 | 17
5 | 11:00 | 10480 | 11
4 | 11:00 | 13214 | 14
3 | 11:00 | 76340 | 17
2 | 11:00 | 15410 | 20
1 | 10:00 | 75000 | 17
我需要找出 id 1 和 3 之间的差异 (76340-75000 = 1340)。
之前尝试过这些:
select
t1.Machine, t1.[ID], t2.[ID], t1.Value, t2.Value,
t2.Value - t1.Value as difference
from
hava t1
cross apply
hava t2
where
t1.Machine = t2.Machine
and t1.ID <> t2.ID
and t1.Machine = 17
但它与 t1.id 相比整个 table。
我无法使用 lag
功能 - 非常感谢您的帮助。
WITH CTE(ID , Time, Value, Machine)AS
(
SELECT 7,'12:00',154400,20 UNION ALL
SELECT 6,'12:00',77840,17 UNION ALL
SELECT 5,'11:00',10480,11 UNION ALL
SELECT 4,'11:00',13214,14 UNION ALL
SELECT 3,'11:00',76340,17 UNION ALL
SELECT 2,'11:00',15410,20 UNION ALL
SELECT 1,'10:00',75000,17
),
CTE2 AS
(
SELECT C.ID,C.TIME,C.Value,C.Machine,
ROW_NUMBER()OVER(PARTITION BY C.MACHINE ORDER BY C.TIME ASC)XCOL
FROM CTE AS C
)
SELECT X.ID,X.Time,X.Value, X2.Value, X.Machine
FROM CTE2 AS X
LEFT JOIN CTE2 AS X2 ON X.Machine=X2.Machine AND X.XCOL=X2.XCOL-1
WHERE X.Machine=17