SQL查询 - 按日期聚合

时间:2013-05-07 07:43:28

标签: sql sql-server

我似乎很难找到问题的正确查询,我们将不胜感激。

我有 2 表:

PatientExercise (PatientID,ExerciseID,StartDate,EndDate)-first 3 are PK

PatientHistory (PatientID,ExerciseID,CompletionDate) -all 3 are PK

我正在尝试构建2个查询。

第一个需要返回给定患者的锻炼完成百分比一周(按天),第二个查询应该在3个月(几周)内完成相同的操作。

例如:

PatientExercise: 此表中没有任何重叠日期(PatientExercise)

PatientID ExerciseID  StartDate    EndDate
---------------------------------------------
111           13     2013-04-28   2013-08-28
111           14     2013-04-28   2013-08-28
111           16     2013-04-28   2013-05-07
111           17     2013-05-09   2013-08-28
222           13     2013-04-28   2013-08-28
222           14     2013-04-28   2013-08-28
.
.
.

PatientHistory

PatientID ExerciseID  CompletionDate 
------------------------------------
111           13     2013-04-28 
111           13     2013-05-05 
111           14     2013-05-05
111           13     2013-05-06 
111           14     2013-05-06
111           13     2013-05-07 
111           14     2013-05-07
111           16     2013-05-07 
111           13     2013-05-08 

for patientID 111,其中包含2013-05-05周日期的开始日期 查询1结果:

day            Completion
-------------------------------
2013-05-05        66%             ->> there are 3 exe's that has to be done on this date (13,14,16) and according to history he did only 2 (13,14) so 2/3 = 66%
2013-05-06        66%
2013-05-07       100%
2013-05-08        50%  
2013-05-09         0%
2013-05-10         0%
2013-05-11         0%

和第二次查询相同,但不是白天 - >周。

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试此查询

根据需要添加周过滤器。

查询1

select CONVERT(datetime,CompletionDate), 100*count(*)/(select count(*) from tbl1
                            where CONVERT(datetime,CompletionDate) 
                                   between CONVERT(datetime,StartDate) 
                                   and CONVERT(datetime,EndDate) and PatientID=111) as completionRate
from 
  tbl2 b
where PatientID=111
group by CONVERT(datetime,CompletionDate)

SQL FIDDLE

|         DATE(COMPLETIONDATE) | COMPLETIONRATE |
-------------------------------------------------
| April, 28 2013 00:00:00+0000 |        33.3333 |
|   May, 05 2013 00:00:00+0000 |        66.6667 |
|   May, 06 2013 00:00:00+0000 |        66.6667 |
|   May, 07 2013 00:00:00+0000 |            100 |
|   May, 08 2013 00:00:00+0000 |             50 |

注意:这不是优化的方式,但它可以工作。你还需要检查0否则它会将0除错。

答案 1 :(得分:0)

试试这个:

;WITH ExercisesNeeded AS(
SELECT
    PatientID,
    COUNT(1) ExercisesNeeded
FROM PatientExercise
WHERE '2013-05-05' BETWEEN StartDate AND EndDate
GROUP BY PatientID
),
ExercisesDone AS(
SELECT PatientID,
       CompletionDate,
       COUNT(ExerciseID) ExercisesDone
FROM PatientHistory
GROUP BY PatientID,
         CompletionDate
)
SELECT
    ED.PatientID,
    CompletionDate,
    ExercisesDone * 100 / NULLIF(ExercisesNeeded, 0) AS PercentDone
FROM ExercisesNeeded EN
JOIN ExercisesDone ED
    ON ED.PatientID = EN.PatientID
WHERE CompletionDate >= '2013-05-05'

SQL FIDDLE