如何在DB2中制作数据透视表?

时间:2019-04-02 08:13:30

标签: database db2 pivot

我有一张桌子,像这样:

Postman

我想做的是计算每周的总人数。 然后按总数进行排序。

我尝试过,GROUP BY可以实现这一目标,但无法解决。

这是我的期望:

| Date      | Week | Name   | No | Count |
|-----------|------|--------|----|-------|
| 2019/4/1  |  14  | John   | 1  | 1     |
| 2019/4/1  |  14  | Mary   | 2  | 1     |
| 2019/4/9  |  15  | Kevin  | 3  | 2     |
| 2019/4/9  |  15  | John   | 4  | 1     |
| 2019/4/9  |  15  | Jessie | 5  | 1     |
| 2019/4/18 |  16  | Kevin  | 6  | 1     |
| 2019/4/18 |  16  | John   | 7  | 1     |
| 2019/4/18 |  16  | Jessie | 8  | 2     |
| 2019/4/18 |  16  | Mary   | 9  | 3     |
| 2019/4/18 |  16  | Mary   | 10 | 1     |
| 2019/4/18 |  16  | Jessie | 11 | 1     |
| 2019/4/24 |  17  | Mary   | 12 | 1     |
| 2019/4/24 |  17  | Jessie | 13 | 1     |

我该怎么办?

1 个答案:

答案 0 :(得分:2)

Select [Name] 
 ,sum(case when [Week] = 14 then [Count] else 0 end) as Week14
 ,sum(case when [Week] = 15 then [Count] else 0 end) as Week15
 ,sum(case when [Week] = 16 then [Count] else 0 end) as Week16
 ,sum(case when [Week] = 17 then [Count] else 0 end) as Week17
 ,sum([Count]) as Total
from [table]
group by [Name]
order by Total

我不确定您使用的是哪个版本的DB2(LUW / zOS / i),所以这是一个一般性的答案。可以使周数更加灵活,但是在周数中需要完成一定数量的硬编码。