我需要帮助从SQL Server表中排序日期并将它们填充到字符串中

时间:2017-12-26 11:33:51

标签: sql sql-server tsql sql-server-2012

我需要帮助按时间顺序排序日期并将它们填充到字符串中。

我有以下查询:

DECLARE @cols AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(FORMAT(WorkDate, 'M/d/yyyy', 'en-US')) 
                    FROM JobScheduleDate
                    WHERE WorkDate >= '12/26/2017' AND WorkDate <= '01/23/2018'
                    ORDER BY ',' + QUOTENAME(FORMAT(WorkDate, 'M/d/yyyy', 'en-US')) 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')
PRINT @cols

JobScheduleDate表具有以下日期:

12/26/2017
12/27/2017
12/28/2017
12/29/2017
1/1/2018
1/2/2018
1/3/2018
1/4/2018
1/5/2018
1/8/2018
1/9/2018
1/10/2018
1/11/2018
1/12/2018
1/15/2018
1/16/2018
1/17/2018
1/18/2018
1/19/2018
1/22/2018
1/23/2018

我的结果如下:

[1/10/2018],[1/11/2018],[1/12/2018],[1/16/2018],[1/17/2018],[1/18/2018],
1/19/2018],[1/2/2018],[1/22/2018],[1/23/2018],[1/3/2018],[1/4/2018],
[1/5/2018],[1/8/2018],[1/9/2018],[12/26/2017],[12/27/2017],[12/28/2017],[12/29/2017]

3 个答案:

答案 0 :(得分:2)

试试这个;

SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(FORMAT(WorkDate, 'M/d/yyyy', 'en-US')) 
                    FROM (select * from JobScheduleDate WHERE WorkDate >= '12/26/2017' AND WorkDate <= '01/23/2018' order by WorkDate) JobScheduleDate 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')

您应该从WorkDate ASC检索有序集合中的数据。

答案 1 :(得分:2)

只使用没有字符串格式化的工作日

DECLARE @cols AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(FORMAT(WorkDate, 'M/d/yyyy', 'en-US')) 
                    FROM JobScheduleDate
                    WHERE WorkDate >= '12/26/2017' AND WorkDate <= '01/23/2018'
                    ORDER BY WorkDate
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'),1,1,'')
PRINT @cols

答案 2 :(得分:2)

最简单的方法是使用ANSI标准格式格式化日期:

SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(FORMAT(WorkDate, 'yyyy-M-d', 'en-US')) 
                      FROM JobScheduleDate
                      WHERE WorkDate >= '2017-12-26' AND WorkDate <= '2018-01-23'
                      ORDER BY ',' + QUOTENAME(FORMAT(WorkDate, 'yyyy-M-d', 'en-US')) 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 1,'');

这将是我的第一个建议。您也可以使用以下格式执行此操作:

SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(FORMAT(WorkDate, 'M/d/yyyy', 'en-US')) 
                      FROM JobScheduleDate
                      WHERE WorkDate >= '2017-12-26' AND WorkDate <= '2018-01-23'
                      GROUP BY ',' + QUOTENAME(FORMAT(WorkDate, 'M/d/yyyy', 'en-US'))
                      ORDER BY MIN(WorkDate)
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 1, '');

这假设WorkDate是日期。如果它有时间组件,则对CAST(WorkDate as date)GROUP BY使用ORDER BY