Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 769
Jonas Avatar asked Jul 04 '12 08:07

Jonas


People also ask

Can we do GROUP BY in CASE statement?

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.

How do I apply GROUP BY condition?

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.

Can we use aggregate function in CASE statement?

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.

Can I use CASE statement in WHERE clause in Oracle?

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 .


1 Answers

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...

like image 166
Ollie Avatar answered Oct 21 '22 06:10

Ollie