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

问题描述 投票:1回答:3

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

我有以下查询:

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]
sql sql-server tsql sql-server-2012
3个回答
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 BYORDER BY


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检索有序集合中的数据。


2
投票

只需使用没有字符串格式的workdate

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
© www.soinside.com 2019 - 2024. All rights reserved.