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