2013-07-17 38 views
1

我的數據是這樣的如何採取計數支點在SQL Server

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但是給空

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 

回答

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