计算具有大于1年分组的行

时间:2015-11-19 16:16:42

标签: sql sql-server sql-server-2008

我目前有查询对id 16 SELECT YEAR(pbd.date_created), COUNT(*) FROM patient_booking_data pbd inner join problems p on pbd.pid = p.pid WHERE p.problem_list_id IN (16) GROUP BY YEAR(pbd.date_created) 有问题的患者进行计数:

date_created

根据他们进入我们系统的年份SELECT YEAR(pbd.date_created), COUNT(*) FROM patient_booking_data pbd inner join problems p on pbd.pid = p.pid WHERE p.problem_list_id IN (16) AND pbd.pid IN ( SELECT pid FROM patient_booking_data GROUP BY pid HAVING count(*) > 1 ) GROUP BY YEAR(pbd.date_created) 对患者数量进行分组。

enter image description here

我想知道在同一年内有多少人返回。

我尝试过这样的事情:

pid

但如果他们重新进入系统即使是不同年份,那么这将计算patient_booking_data(patient_id)。

id | pid | booking_no | date_created | release_date -------------------------------------------------------------------------------- 1 | 565 | 12-3431 | 2012-08-10 | 2012-08-12 2 | 1231 | 12-1125 | 2012-08-11 | 2012-08-28 3 | 831 | 12-7897 | 2012-08-11 | 2012-08-11 4 | 2365 | 12-1254 | 2012-09-02 | 2012-09-03 5 | 565 | 12-5698 | 2012-10-10 | 2012-10-25 看起来像:

> names(mergedData)[3:6]
 [1] "list(V2 = \"tBodyAcc-mean()-X\")" "list(V2 = \"tBodyAcc-mean()-Y\")"
 [3] "list(V2 = \"tBodyAcc-mean()-Z\")" "list(V2 = \"tBodyAcc-std()-X\")" 

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

以下查询将返回所有在同一年内访问过两次或更多次的患者:

SELECT
    pbd.id,
    YEAR(pbd.date_created), 
    COUNT(*)
FROM
    patient_booking_data pbd inner join problems p on pbd.pid = p.pid
WHERE 
    p.problem_list_id IN (16)       
GROUP BY
    YEAR(pbd.date_created), pbd.id
HAVING COUNT(*) > 1

您可以通过在派生表上进行另一组来计算每年此类患者的数量

SELECT COUNT(*), y FROM (
    SELECT
        pbd.id,
        YEAR(pbd.date_created) y
    FROM
        patient_booking_data pbd inner join problems p on pbd.pid = p.pid
    WHERE 
        p.problem_list_id IN (16)       
    GROUP BY
        YEAR(pbd.date_created), pbd.id
    HAVING COUNT(*) > 1
) t1 GROUP BY y