[英]SQL GROUP BY CASE statement with aggregate function
我有一個看起來像這樣的專欄:
CASE
WHEN col1 > col2 THEN SUM(col3*col4)
ELSE 0
END AS some_product
我想把它放在我的 GROUP BY 子句中,但這似乎會導致問題,因為列中有一個聚合函數。 在這種情況下,有沒有辦法按列別名(例如some_product
)進行 GROUP BY,或者我是否需要將其放在子查詢中並對其進行分組?
我的猜測是你並不真的想要GROUP BY
some_product。
這個問題的答案:“有沒有辦法GROUP BY
列別名,如在這種情況下some_product,或者我需要把這個在一個子查詢和組嗎?” 是:您不能GROUP BY
列別名。
在GROUP BY
子句之后才處理分配列別名的SELECT
子句。 內聯視圖或公用表表達式 (CTE) 可用於使結果可用於分組。
內聯視圖:
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 ...
雖然香農的回答在技術上是正確的,但它看起來有點矯枉過正。
簡單的解決方案是您需要將求和放在case
語句之外。 這應該可以解決問題:
sum(CASE WHEN col1 > col2 THEN col3*col4 ELSE 0 END) AS some_product
基本上,您的舊代碼告訴 SQL 分別為每一行執行sum(X*Y)
(讓每一行都有自己無法分組的答案)。
我寫的代碼行采用 sum product,這就是你想要的。
如果您按其他值分組,則不是您所擁有的,
寫成
Sum(CASE WHEN col1 > col2 THEN SUM(col3*col4) ELSE 0 END) as SumSomeProduct
如果你想group By
內部表達式(col3*col4)
那么
編寫group By
以匹配沒有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
最后,如果要按實際聚合分組
Select SumSomeProduct, Count(*), <other aggregate functions>
From (Select <other columns you are grouping By>,
Sum(Case When col1 > col2
Then col3*col4 Else 0 End) as SumSomeProduct
From Table
Group By <Other Columns> ) As Z
Group by SumSomeProduct
我認為答案很簡單(除非我遺漏了什么?)
SELECT
CASE
WHEN col1 > col2 THEN SUM(col3*col4)
ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
WHEN col1 > col2 THEN SUM(col3*col4)
ELSE 0
END
您可以將 CASE STATEMENT 逐字放在 GROUP BY 中(減去別名列名)
在 SAS 中,我可以對聚合表中的“case when”列進行 GROUP BY。 您所要做的就是放置“GROUP BY calculated some_product”。 只需在列名前放置“已計算”和一個空格。 為我工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.