嗨,我有一个这样的表格:
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 并根据 c5 值将 c4 转换为 2 列:
c1 c2 c3 c5_a c5_b
v1 xx xx 1 2
v2 xx xx 3 0
v3 xx xx 2 1
如何在 SQL 中执行此操作?
这可以通过条件聚合来完成,假设分组列为 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
这是对 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;