How Do I Use Case Statement Column In Group By

后端 未结 2 770
无人共我
无人共我 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:10

    You can either use the case as is in the group by, like this:

    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)
    GROUP BY SOME_TABLE_ALIAS.COLUMN1, OTHER_TABLE_ALIAS.COLUMN2, 
    CASE
        WHEN SOME_TABLE_ALIAS.COLUMN3 IS NOT NULL THEN 'A'
        ELSE 'B'
    END
    

    or use a sub-query like this:

    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
    

提交回复
热议问题