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?
The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause. It can be used in the Insert statement as well.
Syntax: SELECT column1, function_name(column2) FROM table_name WHERE condition GROUP BY column1, column2 HAVING condition ORDER BY column1, column2; function_name: Name of the function used for example, SUM() , AVG(). table_name: Name of the table. condition: Condition used.
CASE statement in SQL and aggregate functions Aggregate functions in SQL Server perform calculations and return a single value. Examples of aggregate functions are MIN, MAX, COUNT, ABG and CHECKSUM. For this purpose, we use the COUNT aggregate function in SQL Server.
Introduction to Oracle CASE expression You can use a CASE expression in any statement or clause that accepts a valid expression. For example, you can use the CASE expression in statements such as SELECT , UPDATE , or DELETE , and in clauses like SELECT , WHERE , HAVING , and ORDDER BY .
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With