用于选择 1 列以上的比率的 SQL

sql for selecting ratio over 1 column

提问人:dr jerry 提问时间:11/8/2023 最后编辑:dr jerry 更新时间:11/8/2023 访问量:33

问:

datekey (number) | value (numeric) | other | values
20230101           10003
20230101           -3
20230101           282345
20230101           -3
20230101           285
20230102           10001
20230102           -3
20230102           22345
20230103           3
20230103           -3
20230103           282345

我有上面的表格。我需要对日期键进行查询(在oracle sql中)分组,并选择每个分组日期键的比率,其中值低于特定阈值,与每个分组日期的总金额 我在下面提出了疑问:

WITH tc AS (SELECT DATEKEY/100 AS MONTH, count(*) total
             FROM mytable where DATEKEY/100 >= 202111 GROUP BY DATEKEY/100)
, lc AS (SELECT DATEKEY/100 AS MONTH, count(*) missing 
FROM mytable fsr where DATEKEY/100 >= 202111 AND value < 1000 GROUP BY DATEKEY/100)
SELECT tc.MONTH, tc.total, lc.missing, lc.missing/tc.total AS perc FROM tc, lc WHERE tc.MONTH = lc.MONTH ORDER BY tc.MONTH desc; 

导致:

month.    | total | missing | perc
20230101     5         3        0.60
20230102     3         1        0.3333
20230103     3         2        0.666

但我认为有更干净的方法(没有with),也利用了Oracle的ratio_to_report,但我还没有弄清楚。

SQL Oracle 分组

评论


答:

3赞 Littlefoot 11/8/2023 #1

另一种选择是对缺失值使用条件聚合,对其余值使用普通计数。

SQL> select datekey,
  2    count(*) as total,
  3    sum(case when value < 1000 then 1 else 0 end) as missing,
  4    round(sum(case when value < 1000 then 1 else 0 end) / count(*), 2) as perc
  5  from test
  6  group by datekey;

   DATEKEY      TOTAL    MISSING       PERC
---------- ---------- ---------- ----------
  20230101          5          3         .6
  20230102          3          1        .33
  20230103          3          2        .67

SQL>