How Do I Use Case Statement Column In Group By

后端 未结 2 767
无人共我
无人共我 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
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题