How do I use Group By based on a Case statement in Oracle?

空扰寡人 提交于 2019-12-08 23:45:29

问题


I have an SQL-query where I use Oracle CASE to compare if a date column is less than or greater than current date. But how do I use that CASE-statement in a GROUP BY-statement? I would like to count the records in each case.

E.g.

select
    (case
        when exp_date > sysdate then 1
        when exp_date <= sysdate then 2
        else 3
     end) expired, count(*)
from mytable
group by expired

But I get an error when trying this: ORA-00904. Any suggestions?


回答1:


select
(case
    when exp_date > sysdate then 1
    when exp_date <= sysdate then 2
    else 3
 end) expired, count(*)
from mytable
group by (case
    when exp_date > sysdate then 1
    when exp_date <= sysdate then 2
    else 3
 end)



回答2:


Use an inline view:

SELECT expired,
       count(*)
  FROM (SELECT (CASE
                   WHEN exp_date > SYSDATE THEN 1
                   WHEN exp_date <= SYSDATE THEN 2
                   ELSE 3
                 END) AS expired
          FROM mytable)
GROUP BY expired;

Hope it helps...




回答3:


As an additional input, although it does not relate to this thread, you can also aggregate your case statements without mentioning it in the group by clause.

SELECT
   WORK_ORDER_NUMBER,
   SUM(CASE WHEN STOCK_CODE LIKE 'xxxx' THEN STOCK_QUANTITY ELSE 0 END) AS TOTAL
FROM Table
GROUP BY WORK_ORDER_NUMBER;


来源:https://stackoverflow.com/questions/11325268/how-do-i-use-group-by-based-on-a-case-statement-in-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!