2013-08-30 57 views
2

在Oracle中,給出了以下數據與多計數

+------------+-----+ 
+ STATUS  | GRP + 
+------------+-----+ 
+ Pass  | A + 
+ Fail  | A + 
+ Pass  | A + 
+ Pass  | B + 
+ Fail  | B + 
+ Pass  | C + 
+ bad  | C + 
+------------------+ 

選擇我想獲得以下結果

+---------+-------+-------+-------+ 
+ GRP  | Total + Pass + Fail + 
+---------+-------+-------+-------+ 
+ A  | 3  + 2  + 1  + 
+ B  | 2  + 1  + 1  + 
+ C  | 2  + 1  + 0  + 
+---------+-------+-------+-------+ 

是否有可能與一個SQL查詢做到這一點還是需要創建三個獨立的SQL調用?

+1

這是一個數據透視表。你可能想看看這個:http://www.dba-oracle.com/t_pivot_examples.htm – Barranka

+0

@Barranka - 這不是一個關鍵的問題......爲什麼這個鏈接? – Hogan

+0

爲什麼在列分隔符中有'+'符號而不是'|'?混淆錯字 –

回答

9

你這樣做使用SQL分組,以及COUNT()和SUM()聚合函數。對於SUM,我們使用嵌入式CASE語句的標準SQL「技巧」。

select GRP, COUNT(*) as Total, 
      SUM(CASE WHEN STATUS = 'Pass' THEN 1 ELSE 0 END) AS Pass, 
      SUM(CASE WHEN STATUS = 'Fail' THEN 1 ELSE 0 END) AS Fail 
from table 
group by GRP 

平均 用同樣的招數,以獲取平均明知AVG聚合將忽略任何參數,該參數爲空。

select GRP, COUNT(*) as Total, 
      SUM(CASE WHEN STATUS = 'Pass' THEN 1 ELSE 0 END) AS Pass, 
      SUM(CASE WHEN STATUS = 'Fail' THEN 1 ELSE 0 END) AS Fail, 
      AVG(CASE WHEN STATUS = 'Pass' THEN Score ELSE null END) AS PassAVG, 
      AVG(CASE WHEN STATUS = 'Fail' THEN Score ELSE null END) AS FailAVG, 
from table 
group by GRP 
+0

看起來不錯。如果它是平均值而不是數值,那麼標準的SQL技巧是什麼? –

+0

@ArchimedesTrajano - 所以對另一個分數的平均分爲傳球與失敗? – Hogan

+0

雅我在想這只是一個做的總和與價值否0,然後除以計數使用總和功能你有 –

0

難道你要找的東西?

SELECT s.GRP, (SELECT COUNT(*) FROM stats ss WHERE s.GRP = ss.GRP) AS Total, 
    (SELECT COUNT(*) FROM stats ss WHERE s.GRP = ss.GRP AND ss.status = 'Pass') 
     AS Pass, 
    (SELECT COUNT(*) FROM stats ss WHERE s.GRP = ss.GRP AND ss.status = 'Fail') 
     AS Fail 
FROM stats s GROUP BY GRP;