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

2019-02-12 16:36发布

问题:

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;