查询不包括表达式作为聚合函数的一部分

时间:2015-03-23 13:58:26

标签: mysql sql oracle

表格下面的

是我表格的缩写版本。我想聚合两个具有共同Id的列。安全性的作用无关紧要,但无法从我的select语句中删除它。

INPUT

Security           MValue        BValue          ID 
 ABH23              50             55             1  
 ABH52              20             20             2
 ABH96              30             35             3
 LOH27              80             70             3
 LOH52              10             15             2
 KLO12              70             60             1

OUTPUT

 Security             MValue        BValue          ID 
 Doesn't Matter       120             115            1  
 Doesn't Matter       30              35             2
 Doesn't Matter       110             105            3

SELECT Security,sum(MValue),sum(Bvalue),ID Group BY ID

现在我明白,在聚合之后,一条记录会有多个安全值,但我并不关心在最终输出中选择哪一条,但我确信有办法解决这个问题。

2 个答案:

答案 0 :(得分:2)

只需选择一次使用min()max()

SELECT MIN(Security), sum(MValue), sum(Bvalue), ID
FROM ???
Group BY ID;

答案 1 :(得分:1)

试试这个。

select Security, MValue, BValue, ID  from 
(
SELECT Row_number()over(partition by ID order by ID) as Rn, Security,sum(MValue) over(partition by ID) as MValue,sum(Bvalue) over(partition by ID) as BValue,ID
from  Yourtable
)
Where RN=1