0

我有这张桌子:

 __________________________
| 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  |
+-----------------------------------------+

那可能吗?我坐在这里挠头,但我想不通!

4

2 回答 2

2

你很幸运。数据透视的规则是您仍然需要知道结果集中列的数量和名称,而不必在运行查询时查找它们。只要您知道这一点,就可以了,在这种情况下,您的列被限制在 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
于 2013-06-17T13:46:57.447 回答
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”行的两行。

于 2013-06-17T13:53:46.403 回答