2

我正在使用 SQL Server 2008 R2,我有这个简单的表

在此处输入图像描述

我试图做的是从此表中进行选择并获得以下结果

x |      1     |       2     |      3
--+------------+-------------+------------
1 |   first 1  |    first 2  |    first 3
2 |   Second 1 |    second 2 |    second 3 

我以为可以做到 PIVOT

我对PIVOT使用 PIVOT 和Count(). SUM()AVG()这在我的表中不起作用,因为我试图PIVOTvarchar列上

问题我是否使用了正确的功能?或者我还需要知道什么来解决这个问题?任何帮助将不胜感激

我试过这个没有运气

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 
4

5 回答 5

8

当您使用 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 with Demo。如果每个 都有未知数量的值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);

请参阅带有演示的 SQL Fiddle

于 2013-07-19T19:07:41.167 回答
2

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

于 2013-07-19T19:03:28.007 回答
1

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.

于 2013-07-19T19:03:50.617 回答
1
SELECT *
FROM #test
 PIVOT(MAX(value) FOR y IN ([51],[52],[53]) )as total 
于 2013-07-19T19:04:09.900 回答
1

我给你一个窍门,但它没有意义。

SELECT * FROM
(SELECT x, y-50 as y, value FROM test) src
  PIVOT(max(value) FOR y IN ([1],[2],[3]) )as total
于 2013-07-19T19:10:51.313 回答