2017-06-27 56 views
0

我試圖格式化一個SELECT語句,以便它輸出結合值超過幾列的結果集。SELECT,將具有不同列的行格式化爲共享ID的單個行

我有這樣一個結果:

ID VID PID VALUE 

1 x  1  a 
2 y  1  A 
3 y  2  B 
4 x  2  b 
5 y  3  C 
6 x  3  c 
7 x  4  d 
8 y  4  D 
9 x  5  e 
10 y  5  E 

我可以格式化一個SELECT語句來有效地參加與重複PID S中的值轉換爲單列?我只對PIDVALUE感興趣,

PID VALUE1 VALUE2 

1  a  A 
2  b  B 
3  c  C 
4  d  D 
5  e  E 

否則,我應該用實際JOIN s的作用在同一個表查詢?

我試圖用CASE但最多可以拿到這樣一個結果:

ID VID PID VALUE1 VALUE2 

1 x  1  a  NULL 
2 y  1  NULL  A 
3 y  2  NULL  B 
4 x  2  b  NULL 
5 y  3  NULL  C 
6 x  3  c  NULL 
7 x  4  d  NULL 
8 y  4  NULL  D 
9 x  5  e  NULL 
10 y  5  NULL  E 

查詢我使用的是看起來有點像這樣。

SELECT 
    ID, 
    VID, 
    PID, 
    CASE WHEN VID = 'x' THEN VALUE END VALUE1, 
    CASE WHEN VID = 'y' THEN VALUE END VALUE2 
FROM BIGTABLE 
WHERE PID IN (1, 2, 3, 4, 5) 
AND VID IN ('x', 'y') 

有很多的PIDVID值不在只是1-5和X &ÿ所以我選擇它們從整個表的方式。

回答

1

你的意思是這樣嗎?它被稱爲「條件聚合」。

with 
    resultset (id, vid, pid, value) as (
     select 1, 'x', 1, 'a' from dual union all 
     select 2, 'y', 1, 'A' from dual union all 
     select 3, 'y', 2, 'B' from dual union all 
     select 4, 'x', 2, 'b' from dual union all 
     select 5, 'y', 3, 'C' from dual union all 
     select 6, 'x', 3, 'c' from dual union all 
     select 7, 'x', 4, 'd' from dual union all 
     select 8, 'y', 4, 'D' from dual union all 
     select 9, 'x', 5, 'e' from dual union all 
     select 10, 'y', 5, 'E' from dual 
    ) 
-- End of simulated resultset (for testing purposes only, not part of the solution). 
-- SQL query begins below this line. 
select pid, 
     min(case when vid = 'x' then value end) as value1, 
     min(case when vid = 'y' then value end) as value2 
from  resultset 
-- WHERE conditions, if any are needed - as in your attempt 
group by pid 
order by pid 
; 

PID VALUE1 VALUE2 
--- ------ ------ 
    1 a  A  
    2 b  B  
    3 c  C  
    4 d  D  
    5 e  E  
+0

因此,我必須使用GROUP BY子句的分析/聚合函數來處理這些情況?如果我只嘗試'CASE',我會得到'ORA-00979:不是GROUP BY表達式'。 – Eriol

+1

@Eriol - 每個PID只需要一行,所以你想要聚合('GROUP BY')。如果你進行了聚合,你必須在未被「分組」的列上使用聚合函數(比如'MIN'或'MAX'或'SUM')。在條件聚合中,如這裏所示,一些值將是'NULL',並且它們將被諸如MIN,MAX,SUM等聚合函數忽略。這是您的解決方案和我的解決方案之間的差異從Oracle 11.1開始,您可以使用'PIVOT'運算符,它也是一個聚合(但語法不使用'GROUP BY'子句)。 – mathguy

相關問題