每个grup按col1和sum col2分组?在SQL中,Oracle

时间:2015-09-24 14:37:23

标签: sql oracle

我想提出另一个问题。

所以这是我的疑问:

select COL1, sum(col_a+col_b) as col_name2, count(col) as col_qty from tab

这是我的表:

COL1    col_name2   col_qty
alpha   2              3             
alpha   1              4             
alpha   8              2             
beta    2              5             
beta    6              4            
gamma   1              1             
gamma   2              4             
gamma   1              1             
gamma   1              3             

我需要它如何:

COL1    col_name2   col_qty
alpha   11             9
beta    8              9
gamma   5              9

应该怎么做?

3 个答案:

答案 0 :(得分:0)

如果要选择特定列和聚合函数,则必须按列对结果进行分组。

select COL1, sum(col_a), sum(col_b), sum(col_a + col_b), count(col1) from tab group by COL1

一般情况下:

Select [Columns, aggregate functions] 
from [table] where [condition] 
group by [all columns from select] 
having [condition]

where子句用于按列值过滤,having子句按聚合函数的结果进行过滤。

答案 1 :(得分:0)

使用group by语句:

从选项卡组中按col1选择COL1,sum(col_name2),sum(col_qty)

答案 2 :(得分:0)

你可以尝试这个,它会起作用

select col1,sum(col_name2) as col_name2 ,sum(col_qty) as col_qty
from tab 
group by col1;