0

嗨,我有一张像这样的桌子:

c1 c2 c3 c4 c5
v1 xx xx a  1
v1 xx xx b  2
v2 xx xx a  3
v3 xx xx a  2
v3 xx xx b  1

我想删除 c4 并根据 c4 值将 c5 转移到 2 列中:

c1 c2 c3 c5_a c5_b
v1 xx xx  1     2
v2 xx xx  3     0
v3 xx xx  2     1

我如何在 SQL 中执行此操作?

4

2 回答 2

1

这可以通过条件聚合来完成,假设分组列是 c1,c2,c3。

select c1,c2,c3,
coalesce(max(case when c4='a' then c5 end),0) as c5_a,
coalesce(max(case when c4='b' then c5 end),0) as c5_b
from t
group by c1,c2,c3
于 2017-03-17T13:30:01.830 回答
0

这是对 vkp 答案的轻微调整,但更简单一些:

select c1, c2, c3,
       max(case when c4 = 'a' then c5 else 0 end) as c5_a,
       max(case when c4 = 'b' then c5 else 0 end) as c5_b
from t
group by c1, c2, c3;

此外,目前还不清楚您是否max()想要sum().

注意:这假设xx每行中的值相同。否则,您可能还需要这些聚合函数:

select c1, max(c2) as c2, max(c3) as c3,
       max(case when c4 = 'a' then c5 else 0 end) as c5_a,
       max(case when c4 = 'b' then c5 else 0 end) as c5_b
from t
group by c1;
于 2017-03-17T13:44:06.110 回答