简体   繁体   English

将两列按功能SQL分组

[英]Divide two columns into group by function SQL

If I have the below select query: 如果我有以下选择查询:

select col1, col2, col3, sum(value1) as col4, col5
from table1
group by col1, col2, col3, col5

How to add col6 = col4/col5? 如何添加col6 = col4 / col5?

You cannot access the alias in the SELECT clause. 您不能在SELECT子句中访问别名。 So you have to repeat sum(value1) : 所以你必须重复sum(value1)

select col1, col2, col3, 
       sum(value1) as col4, 
       col5, 
       sum(value1) / col5 as col6
from table1
group by col1, col2, col3, col5

Do the GROUP BY in a derived table: 在派生表中执行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

You can perform operations in the select statement. 您可以在select语句中执行操作。 However, you cannot use the aliases of the SQL statement within it. 但是,您不能在其中使用SQL语句的别名。 So you need to do the calculation for col4 again. 因此,您需要再次对col4进行计算。 Just add sum(value1)/col5 as col6 . 只需将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM