如何在Oracle SQL中显示0的计数?

时间:2017-07-03 19:11:30

标签: sql oracle

我需要创建一个表来确定落入不同订单大小范围的订单数量。但是,我需要在1,001 and Above的订单尺寸范围内显示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;

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

UNPIVOT子句可能是一个优雅的解决方案。

答案 2 :(得分:0)

您只需要创建一个存储桶表,然后“LEFT JOIN&#39;你的数量。

    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;