我有一个患者数据库。将他们的Patient_ID作为标识符,并使用多个Start_Date和Stop_Date药物和Action。
我的问题是如何查询
WHERE action = 1 and start_date BETWEEN '01/10/2012' and '01/10/2013'
and where action = 1 is their FIRST Start_date
治疗表:
Patient_ID
Start_Date Varchar
Stope_Date Varchar
Action Varchar
代码: 1 =开始; 2 =停止; 3 =改变
像:
Patient_ID | Medication_Code |Action| Start_Date | Stop_Date
10001 | Med008 | 2 | 01/01/2010 | 10/08/2012
| Med012 | 1 | 02/09/2013 |
| Med088 | 1 | 22/07/2009 |
10002 | Med003 | 2 | 01/01/2009 | 01/03/2011
| Med012 | 1 | 02/03/2012 |
| Med081 | 1 | 22/07/2013
10011 | Med018 | 2 | 11/02/2010 | 10/08/2012
| Med011 | 1 | 12/09/2013 |
| Med028 | 1 | 25/03/2013
您将观察到患者有多个start_dates。如果我将使用像
这样的东西where start_date between 01/01/2012 and 01/01/2013 and action = 1
它会给我所有action =1 and between 01/01/2012 and 01/01/2013
甚至不是他们拥有的第一个Start_date。
所以在这个例子中是IF ITS A WORKING脚本
Select patient_ID, Start_Date, Action, Medication_code
from Patient
Where start_date EARLIEST 01/01/2012 and 01/01/2013 and action = 1
输出要求:
10002 22/07/2013 1 Med081
10011 25/03/2013 1 Med028
提前致谢...我将待命待遇。
答案 0 :(得分:2)
Select patient_ID
, Start_Date
, Action
, Medication_code
from therapy t1
WHERE action = 1
AND Startdate>=@from
AND Startdate<@to+1
AND Start_Date=(
SELECT MIN(t2.Startdate)
from therapy t2
where t1.patient_ID=t2.patient_ID
and t1.Medication_code=t2.Medication_code)
应该这样做。
答案 1 :(得分:2)
你应该为你想要的结果分组
Select patient_ID, MIN(Start_Date) earliestStartDate, MIN(Action) Action, Medication_code
from Patient
Where start_date EARLIEST 01/01/2012 and 01/01/2013 and action = 1
Group By Patient_id, Medication_code
此代码对患者和药物治疗组进行分组
我做了另一个在datetime值中转换字符串的例子
DECLARE @from datetime, @to datetime
SET @from = '2012-01-01'
SET @to = '2013-12-31'
SELECT patient_ID, CONVERT(datetime, Start_Date, 103), Medication_code, Action
FROM Patient Pat
INNER JOIN (
SELECT patient_ID id, MIN(CONVERT(datetime, Start_Date, 103)) date
FROM Patient
WHERE CONVERT(datetime, Start_Date, 103) between @from and @to
AND action = 1
GROUP BY patient_ID) pat2 ON pat.patient_ID = pat2.id AND
CONVERT(datetime, pat.Start_Date, 103) = pat2.date
LEFT JOIN (
SELECT patient_ID id, MIN(CONVERT(datetime, Start_Date, 103)) EarliestDate--, Medication_code--, MIN(Action) Action
FROM Patient
WHERE CONVERT(datetime, Start_Date, 103) < @from
AND action = 1
GROUP BY patient_ID) pat3 ON
pat.patient_ID = pat3.id
WHERE EarliestDate IS NULL
ORDER BY CONVERT(datetime, Start_Date, 103)
这段代码可以很好地将字符串dd / MM / yyyy转换为datetime。