sql创建数据透视表+行到列

时间:2013-12-19 13:44:52

标签: sql-server pivot

对此进行了一些研究,但未找到一个适合我的例子。

我有一张桌子,图片如下图所示,小提琴here

enter image description here

我想要做的是将行转换为列。我在枢轴上阅读联合国,但我失去了一点。

我希望我的输出为:

enter image description here

使用sql,我该怎么做呢。

这是否必须通过变量来实现?

2 个答案:

答案 0 :(得分:3)

您可以使用PIVOT功能获取结果。如果您具有已知数量的值,则可以对查询进行硬编码,类似于以下内容:

select type, color,
  [1], [1.5], [2], [3], [4]
from
(
  select type, color, length, price
  from items
) d
pivot
(
  max(price)
  for length in ([1], [1.5], [2], [3], [4])
) piv
order by type;

SQL Fiddle with Demo。但是,如果您将拥有未知数量的length值,那么您将需要使用动态SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(length) 
                    from items
                    group by length
                    order by length
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT type, color, ' + @cols + ' 
            from 
            (
              select type, color, length, price
              from items
            ) x
            pivot 
            (
                max(price)
                for length in (' + @cols + ')
            ) p 
            order by type'

execute sp_executesql @query;

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

这是对PIVOT这个表的查询。但是如果您不了解行,则应该知道Length值来定义行need to use dynamic query

SELECT Type,Color,
       MAX(CASE WHEN Length=1 THEN price END) as [1],
       MAX(CASE WHEN Length=1.5 THEN price END) as [1.5],
       MAX(CASE WHEN Length=2 THEN price END) as [2],
       MAX(CASE WHEN Length=3 THEN price END) as [3],
       MAX(CASE WHEN Length=4 THEN price END) as [4]

FROM items
GROUP BY Type,Color

SQLFiddle demo