-1

我似乎很难为我的问题找出正确的查询,任何帮助将不胜感激。

我有2张桌子:

病人锻炼 (PatientID,ExerciseID,StartDate,EndDate)-first 3 are PK

病历 (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
.
.
.

病历

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 

对于带有 2013-05-05 周日期的给定开始的患者 ID 111 查询 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%

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

谢谢!

4

2 回答 2

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 小提琴

|         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 错误。

于 2013-05-07T08:03:46.430 回答
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 小提琴

于 2013-05-07T10:30:04.747 回答