2017-02-14 102 views
1

第一篇文章在這裏,但任何人都可以引導或幫助我瞭解以下問題。對於下表中的「Patient_Table」,我如何找出patient_id 22生病的總天數。Microsoft SQL Server計算連續事件之間的總時間

ID Patient_ID  Listing_Number  Date    Status 
----------------------------------------------------------------- 
1  22    1     01/01/2016  Healthy 
2  22    2     01/11/2016  Sick 
3  34    1     01/13/2016  Healthy 
4  22    3     01/20/2016  Healthy 
5  22    4     01/22/2016  Sick 
6  22    5     01/23/2016  Healthy 

下面是我的邏輯到目前爲止,但我不知道正確的語法。

declare 
@count  int = 1, 
@Days_sicks int = 0 

while @count <= (select max (Listing_number) from Patient_Table where Patient_id = '22') 

begin 
    case 
    when (select status from Patient_Table where Patient_id = '22' and Listing_number = @count) = 'Sick' 
    then @Days_sicks = @Days_sicks + datediff('dd', (select min date from Patient_Table where patient_id = 22 and listing_number > @count and status != 'Sick'), (select date from patient_table where patient_id = 22 and listing_number = @count) 
    else @Days_sicks 
    end as Days_sicks 

set @Count = @Count + 1 
END; 

我也試過這一個,但它不工作得很好,我對條款有問題,跟團

SELECT t1.patient_id, 
    DATEDIFF(dd, 
     t1.date, 
     (SELECT MIN(t3.date) 
     FROM Patient_Table t3 
     WHERE t3.patient_id = t1.patient_id 
     AND t3.date> t1.date) as Days_sicks 
    ) 
FROM Patient_Table t1 
WHERE EXISTS(
    SELECT 'NEXT' 
    FROM Patient_Table t2 
    WHERE t2.patient_id = t1.patient_id 
    AND t2.date> t1.date 
    AND t2.status != 'sick') 
    and t1.patient_id = '22' 

所需的結果

Patient id Days_sicks 
22   10 
+0

什麼是quesiton,min(date)至max(date)的邏輯where status ='Sick'? – McNets

+0

請問能否指定sql-server版本 – AldoRomo88

+0

@why 10?它應該不是11? – CodingYoshi

回答

2

使用lead()功能,然後聚合:

select patient_id, 
     sum(datediff(day, date, coalesce(next_date, getdate()))) 
from (select pt.*, 
      lead(date) over (partition by patient_id order by date) as next_date 
     from patient_table pt 
    ) pt 
where status = 'Sick' 
group by patient_id; 

注意:如果某人現在生病了,那麼這會使用當前日期來結束「生病」狀態。

此外,如果患者多次就診時生病,這將起作用。

+0

謝謝戈登。這工作完美! –

0
Select s.Patient_ID, 
    sum(datediff(day, s.Date, coalesce(h.date, getdate()) totalDaysSick 
From table s left join table h 
    on h.Patient_ID = s.Patient_ID 
    and h.Status = 'Healthy' 
    and s.Status ='Sick' 
    and h.Date = (Select Min(date) from table 
        where Patient_ID = s.Patient_ID 
        and Date > s.Date) 
Group By Patient_Id 
0

您可以按日期使用Lag窗函數和訂單,然後做一個DATEDIFF找到當前和以前的日期之間的天數。然後做一個天數的總和:

select 
    sickdays.Patient_ID 
    ,Sum(sickdays.DayNums) as SickDays 
from 
    (select 
      Patient_ID 
      ,Datediff(day, Lag([Date], 1, null) over (order by [Date]), [Date]) as DayNums 

     from Patient 
     where Patient_ID = 22 
     and Status = 'Sick' 
     group by Patient_ID 
        ,Date) as sickdays 
where 
    sickdays.DayNums is not null 
group by sickdays.Patient_ID