2017-03-17 59 views
0

您好我有这样一个表:SQL格式化行列

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中?

+0

_如何在SQL中执行此操作?_您在SQL中执行了哪些操作? –

+0

您正在使用哪些DBMS? Postgres的?甲骨文? –

回答

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; 
+0

谢谢!你是对的我想要sum()。所以总和将基于c4上的过滤器并在c5上进行求和?我也不清楚为什么你删除了coalesce函数,但仍然得到相同的结果? @戈登Linoof –

+0

@KarlTMuahahaT。 。 。 'else 0'弥补了coalesce()'缺乏。 –

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