我有一个动态SQL查询,它会根据需要返回结果,但唯一的问题是未按正确顺序选择结果数据透视列。
我正在使用SQL Server 2012。
以下是查询:
DECLARE @columns NVARCHAR(MAX), @columns_pivot NVARCHAR(MAX), @sql NVARCHAR(MAX);
SELECT @columns_pivot = COALESCE(@columns_pivot + ', ', '') + QUOTENAME(Week_No)
,@columns = COALESCE(@columns + ', ', '') + 'ISNULL(' + QUOTENAME(Week_No) + ',0) AS ' + QUOTENAME(Week_No) + ''
FROM (SELECT DISTINCT TOP 100 PERCENT DATEPART(wk,T_Date) As Week_No
FROM [VISIT].[dbo].[Report]
WHERE DATEPART(m,T_Date) = 5
ORDER BY Week_No DESC) x; // This query returns Column 'Week_No' in order 22,21,20,19,18 (As Desired)
Edit: //But when Order By Clause is removed it returns 21,18,19,22,20 which is the actual output( Not Desired)
SET @sql = '
SELECT ABC, ' + @columns + '
FROM
(Select TOP 100 PERCENT
ABC
,SUM(CASE WHEN Type = A THEN Sum ELSE 0 END) AS Revenue
,DATEPART(wk,T_Date) As Week_No
FROM [VISIT].[dbo].[Report]
GROUP BY ABC
,DATEPART(wk,T_Date)
ORDER BY Week_No DESC) As j
PIVOT(
max(Revenue)
FOR Week_No in (' + @columns_pivot + ')) As p '
最终结果按ABC,21,18,19,22,20
的顺序返回列但我想要结果如ABC,22,21,20,19,18。
我看到的帖子很少,但无法弄清楚我的查询有什么问题。有人可以指出我必须在Query中更改以获得所需的输出。我究竟要在哪里放置ORDER BY子句
简而言之,当 Select Distinct 语句在Desc订单中返回 Week_No 列时,为什么变量 @columns 和 @columns_pivot < / strong>不按说明顺序获取
感谢。
答案 0 :(得分:0)
我通过将Week_No存储在临时表中并对其应用聚簇索引来解决了该问题。 这是我添加的代码:
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp
SET NOCOUNT ON;
DECLARE @params nvarchar(max) = :month
SELECT DISTINCT TOP 100 PERCENT DATEPART(wk,Tour_Datum) As Week_No into #temp
FROM [VISITOUR].[dbo].[BI_001_ADM_Report]
WHERE DATEPART(m,Tour_Datum) = @params
--Clustered index is created on week_no in acending order, so that data is physically stored in that way
CREATE CLUSTERED INDEX cix_wekno ON #temp(Week_No ASC)