Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with GROUP BY CASE

The following query gives the error "#1241 - Operand should contain 1 column(s)" because of the (Department_Code, Course_Code) line. When I replace that with just (Course_Code) it works. However, that's not what I want

SELECT * FROM Classes
GROUP BY CASE 
WHEN (1) THEN
 Department_Code
 ELSE CASE WHEN (2) THEN 
  (Department_Code, Course_Code)
 ELSE Class_ID
 END
END

How can I group by Department_Code, Course_Code when condition (2) is satisfied?

like image 419
bgcode Avatar asked Aug 16 '10 05:08

bgcode


People also ask

Can I use CASE statement in GROUP BY?

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.

What is the meaning of GROUP BY clause *?

GROUP BY Clause. The GROUP BY clause groups the selected rows based on identical values in a column or expression. This clause is typically used with aggregate functions to generate a single result row for each set of unique values in a set of columns or expressions.


1 Answers

A case expression can only return a single value, so you need two case expressions. Also, use a single case expression for each instead of nesting two inside each other:

SELECT * FROM Classes
GROUP BY
  CASE 
  WHEN (1) THEN
    Department_Code
  WHEN (2) THEN 
    Department_Code
  ELSE
    Class_ID
  END,
  CASE 
  WHEN (2) THEN 
    Course_Code
  ELSE
    1
  END
like image 112
Guffa Avatar answered Nov 14 '22 22:11

Guffa