[英]Divide two columns into group by function SQL
如果我有以下選擇查詢:
select col1, col2, col3, sum(value1) as col4, col5
from table1
group by col1, col2, col3, col5
如何添加col6 = col4 / col5?
您不能在SELECT
子句中訪問別名。 所以你必須重復sum(value1)
:
select col1, col2, col3,
sum(value1) as col4,
col5,
sum(value1) / col5 as col6
from table1
group by col1, col2, col3, col5
在派生表中執行GROUP BY
:
select col1, col2, col3, col4, col5, col4/col5 as col6
from
(
select col1, col2, col3, sum(value1) as col4, col5
from table1
group by col1, col2, col3, col5
) dt
您可以在select語句中執行操作。 但是,您不能在其中使用SQL語句的別名。 因此,您需要再次對col4進行計算。 只需將sum(value1)/col5 as col6
添加sum(value1)/col5 as col6
。
select col1, col2, col3, sum(value1) as col4, col5, sum(value1)/col5 as col6
from table1
group by col1, col2, col3, col5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.