移调列进行,而不总结
问题描述:
我有如下表:移调列进行,而不总结
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月份),我就无法创建该结构,而我不希望这样。有没有什么办法来做到这一点使用枢轴或东西?
答
如果你有,你要保持独特每个月多个值,那么你应该考虑使用PIVOT
一个row_number()
之前应用:
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
结果是:
| NAME | YEAR | CODE | JAN | FEB | MAR |
------------------------------------------
| George | 1991 | 1234 | 675 | 675 | 675 |
| George | 1991 | 1234 | 0 | 675 | 0 |
+0
不错!再一次,谢谢你! – leodamatta 2013-02-18 18:17:59
+0
@leodamatta欢迎您。 – Taryn 2013-02-18 18:19:16
答
使用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])
)
什么味道的数据库 你正在用吗? – Raad 2013-02-18 17:44:52
我正在使用SQL Server – leodamatta 2013-02-18 17:47:17