动作数量

时间:2013-03-18 08:30:14

标签: mysql select count sum union

Helo,我有一张桌子:

from | to   | item | count
-------
Jack | Danie| food | 10
Danie| Maria| food | 2
Jack | Peter| drink| 9
Jack | Danie| water| 1
Danie| Jack | food | 3
Jack | Alise| baks | 4

如何在杰克中找到“物品”的数量?

我的代码:

select sum( q1.count) as s  from (
            SELECT count, item  FROM item_movements WHERE  to = 3
            union All
            SELECT  count*-1, item  FROM item_movements WHERE from =3
            ) q1
group by item
having sum(q1.count) > 0 

我的想法:从中获取所有项目,并将所有项目合并,合并,总结并计算,但如果我添加select count()...则不起作用。

1 个答案:

答案 0 :(得分:0)

没有子查询:

SELECT SUM( IF( `from` = 'Jack', `count`, `count` * -1 ) ) `delta`
FROM `item_movements`
WHERE `from` = 'Jack' OR `to` = 'Jack'

(如果'杰克'和'杰克'之间有任何动作,这将失败)