GROUP BY子句中的Where子句包含范围

时间:2016-05-18 18:47:13

标签: sql-server

我想要一种机制,其中年龄范围的报告案例数量将针对特定日期。但是WHERE子句BioData.[Date] = '05/16/2016'发出了错误。

有人可以帮我修理一下。 我的查询如下:

SELECT  t.[Range] AS [Age Range], COUNT(*) AS [Number of Reported Cases] 
FROM    (
            SELECT
                CASE
                    WHEN Age BETWEEN  0 AND  6 THEN ' 0-6 ' 
                    WHEN Age BETWEEN 07 AND 17 THEN '10-19'
                    WHEN Age BETWEEN 18 AND 60 THEN '20-29'
                    ELSE '60+'
                END AS [Range]
            FROM BioData
        ) t
WHERE   BioData.[Date] = '05/16/2016'
GROUP   BY t.[Range]

1 个答案:

答案 0 :(得分:1)

尝试使用http://www.dpriver.com/pp/sqlformat.htm

等工具重新格式化您的查询
SELECT t.range  AS [Age Range], 
       Count(*) AS [Number of Reported Cases] 
FROM   (SELECT CASE 
                 WHEN age BETWEEN 0 AND 6 THEN ' 0-6 ' 
                 WHEN age BETWEEN 07 AND 17 THEN '10-19' 
                 WHEN age BETWEEN 18 AND 60 THEN '20-29' 
                 ELSE '60+' 
               END AS range 
        FROM   biodata) t 
WHERE  biodata.[Date] = '05/16/2016' 
GROUP  BY t.range 

您意识到[biodata]不存在,因为您的FROM只是[t]

你可能错过了JOIN biodata但是因为你的问题不清楚我猜不出你还需要什么。

编辑:经过一番挖掘,我想你想要这个

SELECT t.range  AS [Age Range], 
       Count(*) AS [Number of Reported Cases] 
FROM   (SELECT CASE 
                 WHEN age BETWEEN 0 AND 6 THEN ' 0-6 ' 
                 WHEN age BETWEEN 07 AND 17 THEN '10-19' 
                 WHEN age BETWEEN 18 AND 60 THEN '20-29' 
                 ELSE '60+' 
               END AS range 
        FROM   biodata
        WHERE  biodata.[Date] = '05/16/2016' ) t 
  --    ^^^ move where inside `t`
GROUP  BY t.range