1

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()... 它不起作用。

4

1 回答 1

0

没有子查询:

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

(如果 'Jack' 和 'Jack' 之间有任何移动,这将失败)

于 2013-03-19T07:04:42.810 回答