我尝试通过 SQL或Access 进行查询以跟踪患者的动作,但真的很挣扎。我面临的问题是,每位患者每天只有一个位置,但患者可以在病房之间往返,因此尝试使用患者/位置并且最大和最小日期是不够的。
示例:
- RowID: 1 Patient A - Ward 10 - 01/01/2015
- RowID: 2 Patient A - Ward 10 - 02/01/2015
- RowID: 3 Patient A - Ward 11 - 03/01/2015
- RowID: 4 Patient A - Ward 10 - 04/01/2015
- RowID: 5 Patient B - Ward 11 - 01/01/2015
正如您所看到的,每天只会捕获一次该位置,但我想开发一个动作,如果max date
grouped by patient and ward
将使用我的 - Patient A - Ward 10 01/01/2015 - 02/01/2015
- Patient A - Ward 11 03/01/2015 - 03/01/2015
- Patient A - Ward 10 04/01/2015 -
- Patient B - Ward 11 01/01/2015 -
将在04的Ward 10上给出最后一个日期/ 01/2015,这在技术上是正确的,但我想在02/01/2015捕获运动。我希望能够显示以下内容:
{{1}}
非常感谢任何帮助
亲切的问候, SIE
答案 0 :(得分:0)
您需要使用相同的表格设置Self Join
并使用条件对齐行,以便它们彼此相邻排列
设定:
SELECT * INTO #TABLE FROM
(
SELECT 1 ROWID, 'Patient A' PAT , 'Ward 10' loc ,'01/01/2015' recorddate UNION ALL
select 2 ROWID, 'Patient A' PAT , 'Ward 10' loc ,'02/01/2015' recorddate UNION ALL
select 3 ROWID, 'Patient A' PAT , 'Ward 11' loc ,'03/01/2015' recorddate UNION ALL
select 4 ROWID, 'Patient A' PAT , 'Ward 10' loc ,'04/01/2015' recorddate UNION ALL
select 5 ROWID, 'Patient B' PAT , 'Ward 11' loc ,'01/01/2015' recorddate) A
查询:
SELECT
A.pat, A.loc, a.recorddate, MIN(b.recorddate)
FROM #table A
INNER JOIN #TABLE B
ON A.PAT=B.pat
and (A.recorddate<B.recorddate)
group by A.ROWID, A.pat, A.loc, a.recorddate
UNION ALL
-- Get the row that donot have a To Date
SELECT A.PAT, LOC , A.recorddate, NULL
FROM #table A
INNER JOIN (SELECT
B.pat, MAX(B.recorddate) recorddate
FROM #table B
GROUP BY B.PAT) B
on A.PAT=B.PAT
and A.recorddate=B.recorddate
结果:
pat loc FROMDATE TODATE
Patient A Ward 10 01/01/2015 02/01/2015
Patient A Ward 10 02/01/2015 03/01/2015
Patient A Ward 11 03/01/2015 04/01/2015
Patient B Ward 11 01/01/2015 NULL
Patient A Ward 10 04/01/2015 NULL