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?
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)
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...
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;