将列转换为行而不进行求和

时间:2013-02-18 17:38:15

标签: sql sql-server pivot

我有下表:

    id     name     year     month     value     code
    1      George   1991       1       675       1234
    2      George   1991       2       675       1234
    3      George   1991       2       675       1234
    5      George   1991       3       675       1234
    ...    ...      ...       ...      ...       ...

但是我必须像这样展示它,所以我可以连续几个月有一个id:

    id     year     name     code     jan     feb     mar     apr   ...  dec
    1      1991     George   1234     675     675     675      0          0
    2      1991     George   1234      0      675      0       0          0
    ...    ...      ...      ...      ...     ...     ...     ...   ...  ...

事情是:同一个月可能有超过1个值,并且我无法在不对值进行求和的情况下创建该结构(在此示例中为2月),我不希望这样。有没有办法使用数据透镜或其他东西?

2 个答案:

答案 0 :(得分:3)

如果您希望每个月保留唯一的多个值,则应在使用row_number()之前考虑应用PIVOT

select name, year, code,
  coalesce([1], 0) as jan,
  coalesce([2], 0) as feb,
  coalesce([3], 0) as mar
from
(
  select name, year, month, value, code,
    row_number() over(partition by name, year, month
                      order by year, month) rn
  from yourtable
) src
pivot
(
  max(value)
  for month in ([1], [2], [3])
) piv

请参阅SQL Fiddle with Demo

结果是:

|   NAME | YEAR | CODE | JAN | FEB | MAR |
------------------------------------------
| George | 1991 | 1234 | 675 | 675 | 675 |
| George | 1991 | 1234 |   0 | 675 |   0 |

答案 1 :(得分:1)

使用PIVOT会出现什么问题?

通过这种查询,当ID,NAME,CODE,YEAR和MONTH之间存在唯一性时,您将获得除外的结果。

select id, name, code, year,
        [1] as JAN,
        [2] as FEB,
        ...
        [11] as NOV,
        [12] as DEC
from (
        select id, name, code, year, month, value
        from <table>
    )
pivot (
    max (value) for month in ([1],[2], ... [11],[12])
)