2017-07-03 155 views
1

我需要創建一個表格來確定落入不同訂單尺寸範圍的訂單數量。但是,我需要爲訂單大小範圍1,001 and Above顯示0的計數,並且在運行我的查詢時不會顯示。如何在Oracle SQL中顯示0的計數?

SELECT "Bucket", COUNT(*) AS "Order Count" 
FROM 
(SELECT CASE 
    WHEN O.QuantityShares <= 100 THEN '0-100' 
    WHEN O.QuantityShares <= 400 THEN '101-400' 
    WHEN O.QuantityShares <= 800 THEN '401-800' 
    WHEN O.QuantityShares <= 1000 THEN '801-1,000' 
    ELSE '1,001 and Above' 
FROM OrderTransactions O) 
GROUP BY "Bucket" 
ORDER BY "Bucket" ASC; 
+1

輸出的所需格式(佈局)是什麼?您在帖子中的查詢沒有意義;你說「...並且當我運行我的查詢時它沒有顯示出來」,但是如果你運行查詢會出現的唯一情況是**錯誤消息**。你有一個子查詢,你可以選擇一個CASE表達式的結果,但是你沒有給它一個別名 - 那麼誰是外部查詢中的「Bucket」?如果您需要幫助,請不要更改您實際運行的查詢 - 我們應該解決您遇到的問題,而不是通過在此處發佈時更改查詢來創建新問題。 – mathguy

回答

0

你可以用一個子查詢做到這一點來定義桶,然後LEFT JOIN

SELECT b.bucket, COUNT(ot.QuantityShres) AS "Order Count" 
FROM (SELECT 0 as lower, 100 as upper, '0-100' as bucket FROM dual 
     SELECT 101, 400, '101-400' FROM dual 
     . . . 
    ) b LEFT JOIN 
    OrderTransactions ot 
    ON ot.QuantityShares BETWEEN b.lower AND b.upper 
GROUP BY b.bucket 
ORDER BY MIN(b.lower) ASC; 
0

你只需要創建一個你的水桶表,然後'左'加入你的數量。

SELECT "Bucket", COUNT(*) AS "Order Count" 
FROM 
(SELECT '0-100' As Bucket 
UNION 
SELECT '101-400' AS Bucket 
UNION 
SELECT '401-800' AS Bucket 
UNION 
SELECT '801-1,000') Buckets 
LEFT JOIN 
(SELECT CASE 
    WHEN O.QuantityShares <= 100 THEN '0-100' 
    WHEN O.QuantityShares <= 400 THEN '101-400' 
    WHEN O.QuantityShares <= 800 THEN '401-800' 
    WHEN O.QuantityShares <= 1000 THEN '801-1,000' 
    ELSE '1,001 and Above' END As Bucket 
FROM OrderTransactions O) QTY 
ON Buckets.Bucket = QTY.Bucket 
GROUP BY Buckets.Bucket 
ORDER BY Buckets.Bucket ASC;