1

我有下表:

    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 月),我就无法创建该结构,我不希望这样。有没有办法使用枢轴或其他东西来做到这一点?

4

2 回答 2

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

结果是:

|   NAME | YEAR | CODE | JAN | FEB | MAR |
------------------------------------------
| George | 1991 | 1234 | 675 | 675 | 675 |
| George | 1991 | 1234 |   0 | 675 |   0 |
于 2013-02-18T17:52:00.340 回答
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])
)
于 2013-02-18T17:49:07.003 回答