SQL GROUP BY CASE statement with aggregate function

后端 未结 4 1849
时光说笑
时光说笑 2020-11-29 02:47

I have a column that looks something like this:

CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END AS some_product

And I would

4条回答
  •  一整个雨季
    2020-11-29 03:36

    My guess is that you don't really want to GROUP BY some_product.

    The answer to: "Is there a way to GROUP BY a column alias such as some_product in this case, or do I need to put this in a subquery and group on that?" is: You can not GROUP BY a column alias.

    The SELECT clause, where column aliases are assigned, is not processed until after the GROUP BY clause. An inline view or common table expression (CTE) could be used to make the results available for grouping.

    Inline view:

    select ...
    from (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
       from ...
       group by col1, col2 ... ) T
    group by some_product ...
    

    CTE:

    with T as (select ... , CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END AS some_product
       from ...
       group by col1, col2 ... )
    select ...
    from T
    group by some_product ... 
    

提交回复
热议问题