如何在同一个表中添加两行和减一行?

时间:2015-12-12 15:48:41

标签: mysql sql plsql

嗨我有像贝娄一样的表格

viewtime   event   id
----------------------
10           end   101
290         prog   101    
20           rew   101

我希望输出像end + prog-rew,即(10 + 290-20)

输出将是:

viewtime   event   id
280         prog   101 

1 个答案:

答案 0 :(得分:1)

一种解决方案是使用带有SUM和CASE WHEN的GROUP BY查询:

SELECT
  id,
  SUM(CASE WHEN event IN ('end', 'prog') THEN viewtime
           WHEN event = 'rew' THEN -viewtime END) AS viewtime
FROM tablename
GROUP BY id