SQL,多行到一列

时间:2013-02-07 14:27:42

标签: sql pivot rows multiple-columns

所以我有以下日期

ID       NAME       MONTH              COUNT

1        David      December2012       500

2        Rob        December2012       320

1        David      January2013        400

2        Rob        January2013        280

我正在努力做到这一点.......

ID       Name       December2012       January2013

1        David      500                400

2        Rob        320                280

我感到困惑的是我想要保留两个列并只旋转其他两个字段。任何人都知道我会怎么做。

非常感谢你的帮助/时间。我从来没有发布其中的一个,非常感谢回复!

2 个答案:

答案 0 :(得分:5)

您没有指定您正在使用的RDBMS。您可以使用带有CASE表达式的聚合函数在所有数据库中透视

select id, name, 
  sum(case when month = 'December2012' then "count" end) December2012,
  sum(case when month = 'January2013' then "count" end) January2013
from yourtable
group by id, name

请参阅SQL Fiddle with Demo

如果您使用的是SQL Server 2005+或Oracle 11g,则可以使用PIVOT功能:

select *
from
(
  select id, name, month, [count]
  from yourtable
) src
pivot
(
  sum([count])
  for month in (December2012, January2013)
) piv

请参阅SQL Fiddle with Demo

在SQL Server中,如果month的值未知,那么您可以使用与此类似的动态SQL:

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(month) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT id, name,' + @cols + ' from 
             (
                select id, name, month, [count]
                from yourtable
            ) x
            pivot 
            (
                sum([count])
                for month in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with Demo

所有版本都会产生结果:

| ID |  NAME | DECEMBER2012 | JANUARY2013 |
-------------------------------------------
|  1 | David |          500 |         400 |
|  2 |   Rob |          320 |         280 |

答案 1 :(得分:0)

由于您没有指定您正在使用的RDBMS,因此您可以执行此操作:

SELECT
  ID,
  NAME,
  MAX(CASE WHEN MONTH = 'December2012' THEN "COUNT" END) AS "December2012",
  MAX(CASE WHEN MONTH = 'January2013'  THEN "COUNT" END) AS "January2013"
FROM Tablename
GROUP BY ID, Name;