我想使用pivot查询的stuff部分按asc顺序对日期进行排序。
示例:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(column_date)--(column_date)
FROM #temp
order by column_date /* Error occured here*/
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
PRINT(@cols)
通过order by子句获取上述脚本附近的错误。
错误详情:
Msg 145, Level 15, State 1, Line 4
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
答案 0 :(得分:5)
试试这个:
您可以按column_date
使用分组,它将返回不同的日期
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(column_date)--(column_date)
FROM #temp
GROUP BY column_date
order by column_date /* Error occured here*/
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
PRINT(@cols)
答案 1 :(得分:2)
我不知道你为什么在没有order by
的情况下使用Top clause
。试试这个..
SELECT @cols = ',' + column_date
FROM (SELECT DISTINCT Quotename(column_date) column_date
FROM #temp) A
ORDER BY column_date
SELECT @cols = RIGHT(@cols, Len(@cols) - 1)