2017-03-17 62 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