我在根据一大堆数据排序数据时遇到问题。我看了很多例子,但似乎没有一个例子可以解决音量问题 - 或许我只是遗漏了一些东西。我在这里看得很清楚:Sort Columns For Dynamic Pivot和PIVOT in sql 2005并找到了很好的建议,但我仍然找不到正确的方法来对我的支点进行排序。
我正在使用以下sql。它使列枢轴转动,但结果需要进行排序以便于阅读:
SELECT a.* INTO #tempA
FROM (SELECT top (5000) id, email, CONVERT(varchar,ROW_NUMBER() OVER
(PARTITION BY email ORDER BY id)) AS PIVOT_CODE FROM Email) a
order by PIVOT_CODE
DECLARE @cols AS NVARCHAR(MAX),
@sql AS NVARCHAR(MAX)
SELECT @cols =STUFF((SELECT DISTINCT ', ' + QUOTENAME(col)
FROM #tempA WITH (NOLOCK)
cross apply
(
SELECT 'id_' + PIVOT_CODE, id
) c (col, so)
group by col, so
--order by col
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @sql = 'SELECT email, '
+@cols+
'INTO ##AnotherPivotTest FROM
(
SELECT email,
col,
value
FROM #tempA WITH (NOLOCK)
cross apply
(
values
(''id_'' + PIVOT_CODE, id)
) c (col, value)
) d
pivot
(
max(value)
for col in ('
+ @cols+
')
) piv'
EXEC (@sql)
SELECT * FROM ##AnotherPivotTest
结果是混乱:
==============================================================================================
| email | id_19 | id_24 | id_2 | id_16 | id_5 | id_9 | id_23 | .... | id_1 | .... | id_10 |
==============================================================================================
| xx@yy.dk | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 1234 | NULL | NULL |
==============================================================================================
我非常希望对ID进行排序 - 从id_1开始。
正如您所看到的,我试图通过'在选择' cols',但这给了我错误:"如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。"如果没有DISTINCT,我会收到另一个错误:"选择列表中的元素数量超过允许的最大数量4096个元素。"
我被卡住了,所以任何帮助都会非常感激!
答案 0 :(得分:1)
不确定导致问题的原因,但是我已经通过将来自tempA的数据插入另一个临时表并在那里订购来解决了我的数据透视表中的订单问题
INSERT INTO #tempB
SELECT * FROM #tempA
ORDER BY PIVOT_CODE
然后选择不同的那样:
SELECT @cols = @cols + QUOTENAME(PIVOT_CODE) + ',' FROM (SELECT DISTINCT PIVOT_CODE FROM #tempB ORDER BY PIVOT_CODE)
SELECT @cols = SUBSTRING(@cols, 0, LEN(@cols)) --trims "," at end
答案 1 :(得分:1)
您也可以使用光标确定您的cols及其顺序
有cols排序的光标
declare @gruppe nvarchar(max)
declare @gruppeSql nvarchar(max)
declare @SQL nvarchar(max)
DECLARE myCustomers CURSOR FOR
select top 10 FirstName from [dbo].[DimCustomer] Order by FirstName
set @gruppeSql = ''
OPEN myCustomers
FETCH NEXT FROM myCustomers INTO @gruppe
IF (@@FETCH_STATUS>=0)
BEGIN
SET @gruppeSql = @gruppeSql +'[' +@gruppe+']'
FETCH NEXT FROM myCustomers INTO @gruppe
END
WHILE (@@FETCH_STATUS<>-1)
BEGIN
IF (@@FETCH_STATUS<>-2)
SET @gruppeSql = @gruppeSql + ',[' +@gruppe+']'
FETCH NEXT FROM myCustomers INTO @gruppe
END
CLOSE myCustomers
DEALLOCATE myCustomers
SET @gruppeSql = replace(@gruppesql,'''','')
/*Select to preview your cols*/
select @gruppeSql
动态支点
SET @SQL = '
Select *
from
(
SELECT SalesAmount, FirstName
FROM [AdventureWorksDW2014].[dbo].[FactInternetSales] a inner join dbo.DimCustomer b on a.CustomerKey = b.CustomerKey
) x
pivot
(
sum(SalesAmount)
for FirstName in ('+@gruppesql+')
) p'
print @sql
exec(@sql)