在SQL中,我需要将种族数量分成几个月

时间:2016-02-25 10:17:10

标签: sql-server-2008

我使用以下代码生成我们在特定月份看到的不同种族群体的数量。

SELECT
  COUNT(a.[_PatientId]) 'Quits set',
  a.Ethnicity
FROM (SELECT
        [_PatientId],
        SUBSTRING(CAST([_Ethnicity] AS VARCHAR),1,50) AS 'Ethnicity'
      FROM [Test].[dbo].[smoking_data$]
      WHERE [_Quit_Date] BETWEEN '2015-10-01' AND '2015-10-31'
     ) a
GROUP BY a.Ethnicity

给出了这个结果:

Quits set   Ethnicity
129         A - White British
1           B - White Irish
6           C - White other
1           F - Mixed White and Asian
2           G - Mixed Other Background
1           L - Asian/Asian British Other 
1           S - Any Other Ethnic Group
3           Unknown
1           Z - Declined

有没有办法让它像现在一样拥有种族,但是每个月都有一个单独的数字列,而不是一次只能做一个月?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT
    YEAR(_Quit_Date) AS Year,
    MONTH(_Quit_Date) AS Month,
    COUNT(*) 'Quits set',
    SUBSTRING(CAST([_Ethnicity] AS VARCHAR),1,50) AS 'Ethnicity'
FROM [Test].[dbo].[smoking_data$]
GROUP BY YEAR(_Quit_Date), MONTH(_Quit_Date), SUBSTRING(CAST([_Ethnicity] AS VARCHAR),1,50)
ORDER BY YEAR(_Quit_Date), MONTH(_Quit_Date)

注意:未经测试。