我不知道会调用什么,但我希望只获取特定字段的第一行。然后我想计算行之间的时间。
在这个例子中,每个患者应该只有1个状态1和1个状态2。这是第一部分。然后我想结合(我想的可能是一个不透明的?)并获得时差......
Patient Status Time Stamp
--------------------------
A Status1 22:36:45
A Status2 23:04:13
A Status2 3:43:13
B Status1 10:22:42
B Status2 10:32:47
C Status1 16:14:30
C Status2 16:43:41
C Status2 17:22:49
这是我想要的结果
Patient Time Between Status 1&2
-------------------------------
A 0:27:28
B 0:10:05
C 0:29:11
答案 0 :(得分:0)
使用分析函数FIRST_VALUE and LAG:
first_value(time_stamp) OVER(PARTITION BY patient, status ORDER BY time_stamp) first_val
lag(time_stamp) OVER(PARTITION BY patient ORDER BY status) previos_val
然后在first_val和previous_value之间得到区别。
示例(在OracleDB上测试):
SELECT * FROM (
SELECT patient, status, time_stamp,
first_value(time_stamp)
OVER(PARTITION BY patient, status ORDER BY time_stamp) first_val,
lag(time_stamp) OVER(PARTITION BY patient ORDER BY status) previos_val
FROM (
SELECT 'A' Patient, 'Status1' status,
to_date('2015-04-07 22:36:45', 'YYYY-MM-DD HH24:MI:SS') time_stamp
FROM dual
UNION ALL
SELECT 'A' Patient, 'Status2' status,
to_date('2015-04-07 23:04:13', 'YYYY-MM-DD HH24:MI:SS') time_stamp
FROM dual
UNION ALL
SELECT 'A' Patient, 'Status2' status,
to_date('2015-04-07 3:43:13', 'YYYY-MM-DD HH24:MI:SS') time_stamp
FROM dual
)
)
WHERE time_stamp = first_val
ORDER BY patient, status;
答案 1 :(得分:0)
您可以使用ROW_NUMBER()获取状态1之后的状态2行。
SELECT A.Patient
,CONVERT(varchar(8),CAST(B.TimeStamp as DATETIME)-CAST(A.TimeStamp as DATETIME),8) as Time
FROM yourtable A
JOIN
(
SELECT Patient,TimeStamp
,ROW_NUMBER() over(partition by Patient ORDER BY Status) as ROWID
FROM yourtable WHERE Status='Status2'
) B
ON A.Patient=B.Patient AND B.ROWID=1
WHERE A.Status='Status1'
ORDER BY A.Patient
<强>输出强>
Patient Time
A 00:27:28
B 00:10:05
C 00:29:11
答案 2 :(得分:0)
只需做一个简单的GROUP BY
,并计算(第一个)status2和(first)status1之间的差异:
select Patient,
min(case when Status = 'Status2' then timestamp end) -
min(case when Status = 'Status1' then timestamp end)
from tablename
group by patient
请注意,我不知道MS SQL Server,因此您可能需要调整时差计算。 (看看其他答案!)