[英]SQL Server 2008 R2 using PIVOT with varchar columns not working
我正在使用SQL Server 2008 R2,我有这个简单的表
我正在尝试做的是从此表中进行选择并获得以下结果
x | 1 | 2 | 3
--+------------+-------------+------------
1 | first 1 | first 2 | first 3
2 | Second 1 | second 2 | second 3
我以为可以用PIVOT
完成
我对PIVOT
并不太了解,我的所有搜索结果都是通过Count()
使用PIVOT找到的。 SUM()
和AVG()
在我的表中不起作用,因为我尝试在varchar
列上进行PIVOT
问题我使用的功能正确吗? 还是我需要了解其他解决问题的方法? 任何帮助将不胜感激
我没有运气尝试过
PIVOT(count(x) FOR value IN ([1],[2],[3]) )as total
PIVOT(count(y) FOR value IN ([1],[2],[3]) )as total // This one is the nearest
of what i wand but instead of the column value values i get 0
这是查询是否有要测试的人
CREATE TABLE #test (x int , y int , value Varchar(50))
INSERT INTO #test VALUES(1,51,'first 1')
INSERT INTO #test VALUES(1,52,'first 2')
INSERT INTO #test VALUES(1,53,'first 3')
INSERT INTO #test VALUES(2,51,'Second 1')
INSERT INTO #test VALUES(2,52,'Second 2')
INSERT INTO #test VALUES(2,53,'Second 3')
SELECT * FROM #test
PIVOT(count(y) FOR value IN ([1],[2],[3]) )as total
DROP TABLE #test
使用PIVOT函数时,IN子句中的值必须与您选择的值匹配。 您当前的数据不包括1、2或3。您可以使用row_number()
为每个x
分配一个值:
select x, [1], [2], [3]
from
(
select x, value,
row_number() over(partition by x order by y) rn
from test
) d
pivot
(
max(value)
for rn in ([1], [2], [3])
) piv;
请参阅带有演示的SQL Fiddle 。 如果每个x
的值数量未知,那么您将要使用动态SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(row_number() over(partition by x order by y))
from test
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT x,' + @cols + '
from
(
select x, value,
row_number() over(partition by x order by y) rn
from test
) x
pivot
(
max(value)
for rn in (' + @cols + ')
) p '
execute(@query);
关键是对文本字段使用最大功能。
查询:
SELECT X, [51] [1], [52] [2], [53] [3]
FROM (select * from test) t
PIVOT(max(Value) FOR Y IN ([51], [52], [53]) )as total
您说value IN ([1],[2],[3])
。 这意味着“如果值精确等于1、2或3,则匹配”。 但是在你的桌子上从来没有。 那里不正确。
SELECT *
FROM #test
PIVOT(MAX(value) FOR y IN ([51],[52],[53]) )as total
我给你个把戏,但是没有意义。
SELECT * FROM
(SELECT x, y-50 as y, value FROM test) src
PIVOT(max(value) FOR y IN ([1],[2],[3]) )as total
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.