2017-04-17 58 views
0

是否有高效對此示例的替代SQL?我不想使用WITH ... AS,這是主要的標準SQL - 替代WITH ... AS

WITH TEMP_TABLE AS (
    SELECT status, COUNT(1) as total FROM XYZ GROUP BY status 
    ) 
SELECT 
     NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'A'),0) AS A_COUNT , 
     NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'B'),0) AS B_COUNT , 
     NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'C'),0) AS C_COUNT , 
     NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'D'),0) AS D_COUNT , 
     NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'E'),0) AS E_COUNT , 
     NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'F'),0) AS F_COUNT 
FROM DUAL; 

我讀到類似的問題,但他們使用其他DDL的東西,我只想要一個基本的SQL語句。

+1

所以,你想知道如何擺脫[CTE(HTTP的://計算器.com/questions/38775056/creating-a-cte-in-oracle)從你的陳述? CTE的功能非常強大和高效......你爲什麼想要擺脫它? – SQLMason

+0

是的,我知道並喜歡它,但理由是騾子平臺不支持它,至少不是一個實際的方式。請檢查此http://stackoverflow.com/a/36877716/2815227 – mCeviker

+0

感謝您的解釋,我不明白 – SQLMason

回答

4

只需使用條件彙總:

SELECT SUM(CASE WHEN STATUS = 'A' THEN 1 ELSE 0 END) AS A_COUNT , 
     SUM(CASE WHEN STATUS = 'B' THEN 1 ELSE 0 END) AS B_COUNT , 
     SUM(CASE WHEN STATUS = 'C' THEN 1 ELSE 0 END) AS C_COUNT , 
     SUM(CASE WHEN STATUS = 'D' THEN 1 ELSE 0 END) AS D_COUNT , 
     SUM(CASE WHEN STATUS = 'E' THEN 1 ELSE 0 END) AS E_COUNT , 
     SUM(CASE WHEN STATUS = 'F' THEN 1 ELSE 0 END) AS F_COUNT 
FROM XYZ ; 

我要指出的是把價值上的不同的行更容易:

select status, count(*) 
from xyz 
group by status; 
+0

在幾秒鐘內的答案:)現在嘗試!在我的情況下,它們是更實際的,他們在同一行,因爲我會truncate結果到一個json對象 – mCeviker

+0

這看起來更快在Oracle謝謝! – mCeviker

2

這是一個簡單的PIVOT查詢

select * 
from (select status from XYZ) 
pivot (
    count(*) for status in (
     'A' as a_count, 'B' as b_count, 
     'C' as c_count, 'D' as d_count, 
     'E' as e_count, 'F' as f_count 
)); 
1

已經給出答案是完美的,你應該使用它們。不過,爲了給大家提供一個通用的解決方案(也許你有能力改變其他查詢),這將是這一個:

SELECT 
    NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'A'),0) AS A_COUNT , 
    NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'B'),0) AS B_COUNT , 
    NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'C'),0) AS C_COUNT , 
    NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'D'),0) AS D_COUNT , 
    NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'E'),0) AS E_COUNT , 
    NVL((SELECT TOTAL FROM TEMP_TABLE WHERE STATUS = 'F'),0) AS F_COUNT 
FROM 
    (SELECT status, COUNT(1) as total FROM XYZ GROUP BY status) TEMP_TABLE;