Trouble with GROUP BY CASE

前端 未结 2 926
梦如初夏
梦如初夏 2021-01-13 06:58

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

相关标签:
2条回答
  • 2021-01-13 07:33

    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
    
    0 讨论(0)
  • 2021-01-13 07:45

    Had the same problem but found a simpler way which was to construct a helper field that can then be referenced in the GROUP BY. Or you can do the same conditional trick placing it in the GROUP BY so long as you Concat the fields.

    SELECT *,
    
    If( 'whatever field to check' = 2 , CONCAT(Department_Code,Course_Code), Course_Code) AS 'group1'
    
    FROM Classes
    GROUP BY group1
    
    0 讨论(0)
提交回复
热议问题