How Do I Use Case Statement Column In Group By

后端 未结 2 768
无人共我
无人共我 2021-02-05 22:40

As stated by the question, I\'m trying to formulate a query that has a case statement in the column results, and then I want to include that column in the query\'s group by stat

2条回答
  •  我在风中等你
    2021-02-05 23:22

    The alias isn't available to use in the GROUP BY because when GROUP BY happens the alias isn't defined yet:

    Here's the order:
    1.FROM
    2.WHERE
    3.GROUP BY
    4.HAVING
    5.SELECT
    6.ORDER BY
    

    You can work around that with:

    SELECT column1,column2,case_column
    FROM (
    SELECT SOME_TABLE_ALIAS.COLUMN1, OTHER_TABLE_ALIAS.COLUMN2,
    CASE
        WHEN SOME_TABLE_ALIAS.COLUMN3 IS NOT NULL THEN 'A'
        ELSE 'B'
    END AS CASE_COLUMN
    FROM SOME_TABLE SOME_TABLE_ALIAS
    ... (other table joins and where clauses)
    ) a
    GROUP BY COLUMN1, COLUMN2, CASE_COLUMN
    

    Or just use the case you use in SELECT in GROUP BY

提交回复
热议问题