SQL GROUP BY CASE statement with aggregate function

后端 未结 4 1870
时光说笑
时光说笑 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:13

    If you are grouping by some other value, then instead of what you have,

    write it as

    Sum(CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END) as SumSomeProduct
    

    If, otoh, you want to group By the internal expression, (col3*col4) then

    write the group By to match the expression w/o the SUM...

    Select Sum(Case When col1 > col2 Then col3*col4 Else 0 End) as SumSomeProduct
    From ...
    
    Group By Case When col1 > col2 Then col3*col4 Else 0 End 
    

    Finally, if you want to group By the actual aggregate

    Select SumSomeProduct, Count(*), 
    From (Select , 
          Sum(Case When col1 > col2 
              Then col3*col4 Else 0 End) as SumSomeProduct
          From Table
          Group By  ) As Z
    Group by SumSomeProduct
    

提交回复
热议问题