1

我的数据是这样的

Grp, DOB

需要这样的输出

Grp | Count of Age b/w (0-61) | Count of Age b/w 62-64 | Count of Age b/w >=65
ABC | 90                      | 100                    | 200

使用下面的 SQL 但给出 null

SELECT * FROM 
    (SELECT GRP, 
        CASE WHEN DATEDIFF(YEAR, dateofbirth, GETDATE()) BETWEEN 0 AND 61 THEN '[0-61]' 
        WHEN DATEDIFF(YEAR, dateofbirth, GETDATE()) BETWEEN 62 AND 64 THEN '[62-64]' 
        WHEN DATEDIFF(YEAR, dateofbirth, GETDATE())>=65 THEN '[>=65]' 
    END AS [age],--dateofbirth, 
ROW_NUMBER() OVER(PARTITION BY member_number ORDER BY dateofbirth ASC) [cnt] 
    FROM TABLE_P P 
INNER JOIN TABLE_A A ON A.P_ID = P.U_ID 
INNER JOIN TABLE_MC MC ON P.G_ID = MC.GRP 
    WHERE DATE_ENTERED BETWEEN '2013-01-01' AND '2013-06-30')X 
PIVOT (SUM([cnt]) FOR age in ([0-61],[62-64],[>=65])) AS pvt
4

1 回答 1

0

为什么要使用枢轴?试试下面的查询:

    SELECT GRP, 
        SUM(CASE WHEN DATEDIFF(YEAR, dateofbirth, GETDATE()) BETWEEN 0 AND 61 THEN 1 ELSE 0 END) AS Cnt_0_61
        SUM(CASE WHEN DATEDIFF(YEAR, dateofbirth, GETDATE()) BETWEEN 62 AND 64 THEN 1 ELSE 0 END) AS Cnt_62_64 
        SUM(CASE WHEN DATEDIFF(YEAR, dateofbirth, GETDATE())>=65 THEN 1 ELSE 0 END) AS Cnt_sup_64
    FROM TABLE_P P
    INNER JOIN TABLE_A A ON A.P_ID = P.U_ID 
    INNER JOIN TABLE_MC MC ON P.G_ID = MC.GRP 
    WHERE DATE_ENTERED BETWEEN '2013-01-01' AND '2013-06-30'
    GROUP BY GRP
于 2013-07-17T19:23:33.377 回答