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

j2cgzkjk  于 2023-11-17  发布在  Oracle
关注(0)|答案(1)|浏览(114)
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)分组上的datekey,并选择每个分组datekey的比率,其中值低于一定的阈值与每个分组日期的总金额我想出了下面的查询:

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,但我还没有能够弄清楚。

byqmnocz

byqmnocz1#

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

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>

字符串

相关问题