SQL 将行重新格式化为列

SQL reformat row to column

嗨,我有一个 table 喜欢:

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 中执行此操作?

这可以通过条件聚合来完成,假设分组列是 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;