SQL Server 2008 R2 using PIVOT with varchar columns not working

妖精的绣舞 提交于 2019-11-29 15:32:34

When you are using the PIVOT function the values inside the IN clause need to match a value that you are selecting. Your current data does not include 1, 2, or 3. You can use row_number() to assign a value for each 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;

See SQL Fiddle with Demo. If you then have a unknown number of values for each x, then you will want to use dynamic 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);

See SQL Fiddle with Demo

Key is to use the Max function for text fields.

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 

Working demo

SELECT *
FROM #test
 PIVOT(MAX(value) FOR y IN ([51],[52],[53]) )as total 

I give you a trick but it hasn't meaning.

SELECT * FROM
(SELECT x, y-50 as y, value FROM test) src
  PIVOT(max(value) FOR y IN ([1],[2],[3]) )as total

You say value IN ([1],[2],[3]). This means "match if value is exactly equal to 1, 2 or 3". But in your table it never is. Something is not right there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!