按日期分组按月,年

时间:2014-06-23 02:53:28

标签: sql sql-server tsql

我这里有一个样本data。我之前已经问过here,但是当我进一步测试时,我忘记了我还应该考虑Year这个事实。

简而言之,我想按月范围对记录进行分组。 AugJan(第1组)和FebJuly(第2组)。因为我想count每6个月创建多少个学校对象。一个正在发展的趋势是具体的。

结果集如:

+-----------+-------+---------------+
| sc_object | count | range         |
+-----------+-------+---------------+
| pencil    | 1     | 2013-8 2014-1 |
| eraser    | 1     | 2014-2 2014-7 |
| pencil    | 1     | 2014-2 2014-7 |
| sharpener | 1     | 2014-2 2014-7 |
| pencil    | 1     | 2014-8 2015-1 |
| eraser    | 1     | 2015-2 2015-7 |
| pencil    | 1     | 2015-2 2015-7 | 
| sharpener | 1     | 2015-2 2015-7 |
| eraser    | 1     | 2015-8 2016-1 | 
| sharpener | 2     | 2016-2 2016-7 | 
| pencil    | 1     | 2016-2 2016-7 |
| sharpener | 1     | 2016-8 2017-1 |
| eraser    | 1     | 2016-8 2017-1 |
+-----------+-------+---------------+

任何帮助都会很高兴得到赞赏。非常感谢你!

1 个答案:

答案 0 :(得分:3)

您可以执行以下操作(http://www.sqlfiddle.com/#!3/41ac6/19):

WITH cteRanges
AS
(
    SELECT
            site,
            CASE
              WHEN MONTH(date) IN (1) THEN CAST(YEAR(date) - 1 AS VARCHAR(4)) + '-8' + ' ' + CAST(YEAR(date) AS VARCHAR(4)) + '-1'
              WHEN MONTH(date) IN (8, 9, 10, 11, 12) THEN CAST(YEAR(date) AS VARCHAR(4)) + '-8' + ' ' + CAST(YEAR(date) + 1 AS VARCHAR(4)) + '-1'
              ELSE CAST(YEAR(date) AS VARCHAR(4)) + '-2' + ' ' + CAST(YEAR(date) AS VARCHAR(4)) + '-7'
            END AS range
    FROM
            test
)

SELECT
          site,
          COUNT(*),
          range
FROM
          cteRanges
GROUP BY
          site,
          range
ORDER BY
          range,
          site;

您可以根据月份和年份计算范围,然后汇总结果。