3

MySQLテーブルを次のように設定しています。

debts

--------------------------
owed_by | owed_to | amount
--------|---------|-------
Alice   | Bob     | 5
Bob     | Jane    | 10
Alice   | Jane    | 10
Jane    | Bob     | 5

MySQLで、各人が支払うべき金額の合計を返すクエリを作成することは可能ですか?彼らが誰に借りているかは重要ではありません、私はただ一人一人を返したいと思いますそして(総人が負っている-総人が負っている)

未払い額を取得するのは簡単です

SELECT `owed_by`, SUM(`amount`) as 'Total Debt'
FROM `debts`
GROUP BY `owed_by`
ORDER BY SUM(`amount`) DESC

しかし、私は彼らが負っているものを差し引く方法を理解することはできません。

また、原則として、MySQL(可能な場合)またはPHPでこのようなアクションを実行する方が良いですか?

これが私のサンプルデータを含むSQLフィドルです:http ://sqlfiddle.com/#!2/dd7cf/1

4

4 に答える 4

3

あなたは両方の側を組み合わせることができます:

select Person, sum(debt) as 'Total Debt'
from (
    select owed_by as 'Person', amount as 'debt'
    from debts
    union all
    select owed_to, -1*amount
    from debts
) as q
group by Person;
于 2012-09-25T13:43:40.133 に答える
2
SELECT owed.owed_by, owed.amount - coalesce(owns.amount, 0) as `Total Debt`
FROM (
        select owed_by, sum(amount) as amount
        from debts
        group by owed_by
    ) owed
    left join (
        select owed_to, sum(amount) as amount
        from debts
        group by owed_to
    ) owns on owed.owed_by = owns.owed_to
ORDER BY `Total Debt` DESC
于 2012-09-25T13:48:04.533 に答える
1
SELECT od.person, od.amount - COALESCE(ow.amount, 0) AS balance  
FROM (SELECT owed_to AS person, SUM(amount) AS amount FROM debts GROUP BY owed_to) od  
LEFT OUTER JOIN (SELECT owed_by AS person, SUM(amount) AS amount FROM debts GROUP BY owed_by) ow  
ON od.person = ow.person
UNION  
SELECT owed_by, SUM(amount) * (-1) FROM debts   
WHERE owed_by NOT IN (SELECT DISTINCT owed_to FROM debts)   
GROUP BY owed_by; 
于 2012-09-25T13:58:37.840 に答える
0
SELECT `owed_by`, SUM(`amount`) as 'Total Debt'.
(select sum(amount) from debts d2 where d1.owed_by = d2.owed_to) as `Total Plus`
FROM `debts` d1
GROUP BY `owed_by`
ORDER BY SUM(`amount`) DESC
于 2012-09-25T13:29:02.100 に答える