需要一个切换列的查询

时间:2013-06-17 13:41:01

标签: sql pivot

我有这张桌子:

 __________________________
| id1 | id2 | count | time |
|-----|-----|-------|------| 
| abc | def |   10  |   3  |
| abc | def |   5   |   1  |
| ghi | jkl |   2   |   3  |
+--------------------------+

id1和id2是varchar,count是int,time是int。

id1和id2一起构成主键。

时间可以是1,2,3,4或5,具体取决于添加项目的时间(非唯一)。

我想编写一个查询,为我提供此输出:

 _________________________________________
| id1 | id2 |  1  |  2  |  3  |  4  |  5  |
|-----|-----|-----|-----|-----|-----|-----| 
| abc | def |  5  |  0  |  10 |  0  |  0  |
| ghi | jkl |  0  |  0  |  2  |  0  |  0  |
+-----------------------------------------+

这可能吗?我坐在这里挠挠脑袋,但我无法弄明白!

2 个答案:

答案 0 :(得分:2)

你很幸运。 pivot 的规则是,您仍然需要知道结果集中列的数量和名称,而无需在运行查询时查找它们。只要你知道,你就可以了,在这种情况下你的列被限制在1到5的范围内。

有几种方法可以像这样转动。我还是更喜欢sum(case)方法:

select id1, id2, 
    sum(case when time = 1 then [count] else 0 end) "1",
    sum(case when time = 2 then [count] else 0 end) "2",
    sum(case when time = 3 then [count] else 0 end) "3",
    sum(case when time = 4 then [count] else 0 end) "4",
    sum(case when time = 5 then [count] else 0 end) "5"
from [table]
group by id1, id2

另一个选项是PIVOT关键字:

select id1,id2,[1],[2],[3],[4],[5] 
from [table]
PIVOT ( SUM([count]) FOR time IN ([1],[2],[3],[4],[5]) ) As Times

答案 1 :(得分:0)

这样的事情:

select ID1, ID2, 
sum(f1) as '1',
sum(f2) as '2',
sum(f3) as '3',
sum(f4) as '4',
sum(f5) as '5'
from (  select ID1, ID2,
        case when time =1 then time else 0 end as 'f1',
        case when time =2 then time else 0 end as 'f2',
        case when time =3 then time else 0 end as 'f3',
        case when time =4 then time else 0 end as 'f4',
        case when time =5 then time else 0 end as 'f5'
        from dbo._Test
    ) as v
group by ID1, ID2

内部查询为每个时间值提供列,外部查询对值进行求和,因此您不会为“abc”+“def”行获取两行。