SQL GROUP BY CASE statement with aggregate function

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

    While Shannon's answer is technically correct, it looks like overkill.

    The simple solution is that you need to put your summation outside of the case statement. This should do the trick:

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

    Basically, your old code tells SQL to execute the sum(X*Y) for each line individually (leaving each line with its own answer that can't be grouped).

    The code line I have written takes the sum product, which is what you want.

提交回复
热议问题