我在Microsoft SQL Server 2005 Management Studio中工作。我是T-SQL的新手,我必须做出以下报告:
我有一张表(H2O),其中包含时间戳,pumpstatus,tankVolume的记录。
每1分钟将数据插入H2O中。
我必须在清空水箱上做一个报告(基于date1和date2之间的时间戳)。
清空过程开始时的指示器是泵状态从2到3的变化
清空过程结束时的指示器是泵状态从3到2的变化
感谢您的帮助!
答案 0 :(得分:1)
试试这个:
;WITH cte (dt, st, v) AS
(SELECT timestamp AS dt, status AS st, volume AS v
FROM h2o)
SELECT DISTINCT h.timestamp
, h.status
, h.volume
FROM cte c
INNER JOIN h20 h ON h.dt > c.dt AND ((c.st = 2 AND h.status = 3) OR (c.st = 3 AND h.status = 2))
您可以使用时间戳和状态列以及日期高于上一记录以及状态从2更改为3或从3更改为2来加入自身。
答案 1 :(得分:0)
;WITH cte ([emptying time], [Initial Volume], Volume) AS
(SELECT (SELECT TOP 1 H2O_1.[timestamp]
FROM [H2O] H2O_1
WHERE H2O_1.[H2O_TOOLS_P2_JY_TREND_VAL0] = 2
AND H2O_1.[timestamp] < H2O_2.[timestamp]) AS [emptying time],
(SELECT TOP 1 H2O_1.H2O_LT301_VOL_VAL0
FROM [H2O] H2O_1
WHERE H2O_1.[H2O_TOOLS_P2_JY_TREND_VAL0] = 2
AND H2O_1.[timestamp] < H2O_2.[timestamp]) AS [Initial Volume],
H2O_2.H2O_LT301_VOL_VAL0 As Volume
FROM [H2O] H2O_2
WHERE H2O_2.H2O_TOOLS_P2_JY_TREND_VAL0 = 3
)
Select Distinct c.[emptying time],
max(c.[Initial Volume]) as [Initial Volume],
min(c.Volume) as [Final Volume],
(max(c.[Initial Volume]) - min(c.Volume)) as [Emptying volume]
from cte c
group by c.[emptying time]