oracle 在多个CASE子句中计算同一列值

vcirk6k6  于 2023-11-17  发布在  Oracle
关注(0)|答案(2)|浏览(115)

我试图写一个case语句,它在多个when/then迭代中使用一个共享列值,这是不起作用的,因为共享值只在第一个true求值中计算。

select report_month,
       case when (payment_disposition = 'Free Trial' or payment_disposition = 'Pre-paid') then 'Gross Starts'
            when (payment_disposition = 'Payup' or payment_disposition = 'Pre-paid') then 'Net Starts' end as starts,
            sum(num_orders)

字符串
只是正确地将“预付”付款处理汇总到总启动中,我希望将其计算在两者中。是否有一种方法可以在单个查询中完成此操作,而无需嵌套任何内容或编写CTE来分别评估这两种情况?
上面的查询只聚合了第一个定义中的共享payment_disposal,而不是两者都是。我研究了在表上做自连接(这样我就可以在case语句中每个子句使用一个版本的payment_disposal),但是返回的结果太多了,没有意义。

bbuxkriu

bbuxkriu1#

我相信实现这一点的唯一方法是连接一个子查询,然后选择这些结果,或者 Package 整个查询使其成为一个子查询,然后从中构建结果。
我还没有找到一种方法,让结果从一个列到另一个列。

jgwigjjp

jgwigjjp2#

使用条件聚合并将数据作为两列而不是两行:

SELECT report_month,
       SUM(
         CASE
         WHEN payment_disposition IN ('Free Trial', 'Pre-paid')
         THEN num_orders
         END
       ) AS gross_starts,
       SUM(
         CASE
         WHEN payment_disposition IN ('Payup', 'Pre-paid')
         THEN num_orders
         END
       ) AS net_starts
FROM   table_name
GROUP BY
       report_month;

字符串
其中,对于样本数据:

CREATE TABLE table_name(report_month, payment_disposition, num_orders) AS
SELECT DATE '1970-01-01', 'Free Trial', 1 FROM DUAL UNION ALL
SELECT DATE '1970-01-01', 'Pre-paid',   2 FROM DUAL UNION ALL
SELECT DATE '1970-01-01', 'Payup',      3 FROM DUAL UNION ALL
SELECT DATE '1970-02-01', 'Free Trial', 4 FROM DUAL UNION ALL
SELECT DATE '1970-02-01', 'Pre-paid',   5 FROM DUAL UNION ALL
SELECT DATE '1970-02-01', 'Payup',      6 FROM DUAL;


产出:
| 报告_月|总启动数|NET_STARTS|
| --|--|--|
| 1970-01-01 00:00:00| 3 | 5 |
| 1970-02-01 00:00:00| 9 | 11 |
如果你想把它分成两行,那么UNPIVOT

SELECT *
FROM   (
  SELECT report_month,
         SUM(
           CASE
           WHEN payment_disposition IN ('Free Trial', 'Pre-paid')
           THEN num_orders
           END
         ) AS gross_starts,
         SUM(
           CASE
           WHEN payment_disposition IN ('Payup', 'Pre-paid')
           THEN num_orders
           END
         ) AS net_starts
  FROM   table_name
  GROUP BY
         report_month
)
UNPIVOT (
  num_orders FOR starts IN (
    gross_starts AS 'Gross Starts',
    net_starts   AS 'Net Starts'
  )
);


对于样本数据,输出:
| 报告_月|开始|订单数量|
| --|--|--|
| 1970-01-01 00:00:00|毛开工数| 3 |
| 1970-01-01 00:00:00|净启动| 5 |
| 1970-02-01 00:00:00|毛开工数| 9 |
| 1970-02-01 00:00:00|净启动| 11 |
fiddle

相关问题