所以,我有这个问题:
SELECT curr, from, to, SUM(amount) AS total
FROM transfer
GROUP BY curr, from, to
ORDER BY curr, from
结果如下:
| curr | from | to | total |
| USD | A | B | 1200.00 |
| USD | B | A | 500.00 |
我想要的是:
| curr | from | to | total |
| USD | B | A | 700.00 |
A发送1200到B和B发送500到A.所以B仍然欠700到A。
换句话说,当你通过curr,from和to对它们进行分组时,我希望得到结果之间的差异。请记住,只有价值观的IF' A'或者' B'不起作用,因为FROM和TO有很多其他选择。
这甚至可以在MySQL查询中使用吗?我也希望在Doctrine中实现这一目标。
答案 0 :(得分:1)
想象一下从0开始。如果钱从A发送到B,则应该添加。如果从B向A发送资金,则应将其删除。
您可以使用MySQL在SUM()函数内部使用CASE语句来完成此操作,这将根据需要添加/减去金额。试试这个:
SELECT
SUM(
CASE WHEN from = 'A' AND to = 'B' THEN amount
WHEN from = 'B' AND to = 'A' THEN 0 - amount END)
AS total
FROM myTable;
以下是SQL Fiddle示例。
答案 1 :(得分:0)
<强>解释强>
SELECT
T1.curr,
IFNULL(T2.from,T1.to) as `from`,
IFNULL(T2.to,T1.from) as `to`,
IFNULL((T1.total - T2.total),T1.total) as total
FROM
(
SELECT curr,`from`,`to`,SUM(total) as total
FROM transfer T1
GROUP BY curr,`from`,`to`
) T1
LEFT JOIN (
SELECT curr,`from`,`to`,SUM(total) as total
FROM transfer T1
GROUP BY curr,`from`,`to`
) T2
ON T1.curr = T2.curr AND T1.from = T2.to AND T1.to = T2.from
HAVING total > 0
ORDER BY curr
这是SQL Fiddle。