1

我有一个病人数据库。以他们的 Patient_ID 作为标识符,并具有多个药物和操作的 Start_Date 和 Stop_Date。

我的问题是如何查询

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。

所以在这个例子中,如果它是一个工作脚本

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

在此先感谢...我将随时待命。

4

2 回答 2

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)

应该这样做。

于 2013-10-22T11:42:46.537 回答
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

此代码将患者和药物组合在一起

我做了另一个转换日期时间值中的字符串的例子

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 转换为日期时间很好。

于 2013-10-22T11:43:27.913 回答