使用基于集合的方法在SQL Server中按月分类所有日期

时间:2017-10-08 09:02:24

标签: sql sql-server sql-server-2014

我有这样的结果集:

---------------------------
|        AllDates         |
---------------------------
| 2017-05-12 00:00:00.000 |
| 2017-05-14 00:00:00.000 |
| 2017-08-10 00:00:00.000 | 
| 2017-08-13 00:00:00.000 |
| 2018-02-12 00:00:00.000 | 
| 2018-05-15 00:00:00.000 | 
| 2018-05-16 00:00:00.000 |
---------------------------

现在我需要使用SQL Server将所有日期分类为以下字符串

--------------------------------------------------
|                   Result                       |
--------------------------------------------------
| May: 12, 14, Aug: 10, 13, Feb: 12, May: 15, 16 |
--------------------------------------------------

在SQL Server中不使用用户定义的函数,只能通过使用基于集合的方法来实现吗?

1 个答案:

答案 0 :(得分:1)

对于SQL Server 2014,您可以使用:

DECLARE @DataSource TABLE
(
    [value] DATETIME2
);

INSERT INTO @DataSource ([value])
VALUES ('2017-05-12 00:00:00.000')
      ,('2017-05-14 00:00:00.000')
      ,('2017-08-10 00:00:00.000')
      ,('2017-08-13 00:00:00.000')
      ,('2018-02-12 00:00:00.000')
      ,('2018-05-15 00:00:00.000')
      ,('2018-05-16 00:00:00.000');

WITH DataSource AS
(
    SELECT YEAR([value]) AS [Year]
          ,MONTH([value]) AS [MonthID]
          ,DATENAME(MONTH, [value]) AS [Month]
          ,DAY([value]) AS [Day]
    FROM @DataSource
),
DataSourceDays AS
(
    SELECT DISTINCT [Year]
                   ,[MonthID]
                   ,[MONTH] + ':' + [value] AS [Days]
    FROM DataSource T
    CROSS APPLY
    (
        SELECT STUFF
        (
            (
                SELECT ',' + CAST([Day] AS VARCHAR(2))
                FROM DataSource S
                WHERE T.[Year] = S.[Year]
                    AND T.[MonthID] = S.[MonthID]
                ORDER BY [Day]
                FOR XML PATH(''), TYPE
            ).value('.', 'VARCHAR(MAX)')
            ,1
            ,1
            ,''
        )
    ) DS([value])
)
SELECT STUFF
(
    (
        SELECT ', ' + CAST([Days] AS VARCHAR(12))
        FROM DataSourceDays
        FOR XML PATH(''), TYPE
    ).value('.', 'VARCHAR(MAX)')
    ,1
    ,2
    ,''
);

在第一个CTE中,我们将获得我们将要连接的详细信息。在第二个,我们连接每个月和每年的日子。最后,我们将以前的所有结果联系起来。

而且仅供参考,这是使用SQL Server 2017完成同样的事情:

WITH DataSource AS
(
    SELECT YEAR ([value]) AS [Year] 
          ,MONTH([value]) AS [Month]
          ,DATENAME(MONTH, [value]) + ':' + STRING_AGG(DAY([value]), ', ') WITHIN GROUP (ORDER BY [value]) AS [value]
    FROM @DataSource
    GROUP BY YEAR ([value]) 
            ,MONTH([value])
            ,DATENAME(MONTH, [value])
)
SELECT STRING_AGG([value], ' ,') WITHIN GROUP (ORDER BY [Year], [Month])
FROM DataSource;