将两列按功能分组SQL
Divide two columns into group by function SQL
如果我有以下 select 查询:
select col1, col2, col3, sum(value1) as col4, col5
from table1
group by col1, col2, col3, col5
如何添加col6 = col4/col5?
您可以在select 语句中执行操作。但是,您不能在其中使用 SQL 语句的别名。因此,您需要再次对 col4 进行计算。只需添加 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
您无法访问 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
在派生的 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
如果我有以下 select 查询:
select col1, col2, col3, sum(value1) as col4, col5
from table1
group by col1, col2, col3, col5
如何添加col6 = col4/col5?
您可以在select 语句中执行操作。但是,您不能在其中使用 SQL 语句的别名。因此,您需要再次对 col4 进行计算。只需添加 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
您无法访问 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
在派生的 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