如何使用pivot在sql查询中将列转换为行

时间:2014-07-15 09:35:43

标签: sql-server pivot

使用查询select Size,ColorName,QNTY from tbl1

我得到了下表

enter image description here

现在我想以下列格式获取表格

enter image description here

如何使用pivot

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT *
FROM (SELECT Size, ColorName, Qnty
      FROM YourTable)p
      PIVOT (SUM(Qnty) FOR Size IN ([34],[32],[30])Pvt

为了在查询后使用动态数据透视:

DECLARE @columns NVARCHAR(1000) = '',
        @sql NVARCHAR(MAX)

SELECT @Columns = STUFF((SELECT ',['+Size+']'
                        FROM (SELECT DISTINCT Size FROM YourTable)z
                        FOR XML PATH('')),1,1,'')


SET @sql = 'SELECT * 
            FROM (SELECT Size, ColorName, Qnty
                  FROM YourTable)p
            PIVOT (SUM(Qnty) FOR Size IN ('+@columns+')Pvt'

EXECUTE(@sql)

答案 1 :(得分:1)

试试这个

<强> Live Demo

Mathod 1:

SELECT * FROM 
(
  SELECT Size, ColorName, Qnty
  FROM Table1
)p
PIVOT 
(
 Max(Qnty) 
 FOR Size IN ([34],[32],[30])
)Pvt

方法2:

DECLARE @QuestionList nvarchar(max);
DECLARE @qry nvarchar(max);

SELECT @QuestionList = STUFF((SELECT ',['+ CAST(Size AS nVarchar(max))+']'
                        FROM (SELECT DISTINCT Size FROM Table1)z
                        FOR XML PATH('')),1,1,'')

SET @qry = 'SELECT * FROM 
            (SELECT ColorName, Qnty, Size FROM Table1
            )X PIVOT (MAX(Qnty) FOR Size IN (' + @QuestionList + ')) pvt
            ORDER BY Colorname;';

Exec sp_executesql @qry;

方法3:

SELECT ColorName,
       MAX(CASE WHEN Size = 34 THEN Qnty END) AS [34],
       MAX(CASE WHEN Size = 32 THEN Qnty END) AS [32],
       MAX(CASE WHEN Size = 30 THEN Qnty END) AS [30]
FROM Table1
GROUP BY ColorName;