SQL条件聚合

时间:2018-05-01 19:41:20

标签: sql conditional aggregate

我有一张桌子:

items status count date
----- ------ ----- ----------
apple good   100   01/02/2017
apple good   200   03/02/2017
apple bad    50    02/02/2017
pear  good   100   04/02/2017

结果,我希望根据状态汇总计数并显示每个项目的最新日期:

items  count  date
-----  -----  ----------
apple  250    03/02/2017
pear   100    04/02/2017

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT items, SUM(count) count, MAX(date) date
FROM table
GROUP BY items

如果你想为每个状态分别求和,那么:

SELECT items, status, SUM(count) count, MAX(date) date
FROM table
GROUP BY items, status

答案 1 :(得分:0)

使用sum,max和group by以及适用于总和正确好坏的情况

select items, sum(case when status = 'good' then count else -count end), max(date)
from my_table 
group by itmes

或者如果你不需要基于好的和坏的相对金额

select items, sum( count ), max(date)
from my_table 
group by itmes

答案 2 :(得分:0)

我想你只是想:

select items, sum(count), max(date)
from t
group by items;