这涉及三列'name'、'trans_status'、'amount'。我需要得到一个表,其中每个“名称”都在一行上,并且对于四种状态(新、待定、最终、关闭)中的每一种都有一个 SUM() 的所有金额。
这就是我要找的东西:
name total_new total_pending total_final total_closed
Frank 145.35 219.34 518.23 9588.33
Susan 233.54 455.44 920.00 9600.52
这是我的桌子的样子:
transactions
================
userid status amount
----------------------------------
1 new 25.00
1 new 30.18
2 final 90.12
1 pending 100.25
2 new 81.43
users
================
userid name
----------------------------------
1 Frank
2 Susan
我尝试了很多不同的查询,但恐怕我超出了我的能力范围。这是一个失败的例子:
SELECT a.userid, u.name,
( SUM(a.amount)
WHERE a.status = 'new'
) AS total_new,
( SUM(a.amount)
WHERE a.status = 'pending'
) AS total_pending,
( SUM(a.amount)
WHERE a.status = 'final'
) AS total_final,
( SUM(a.amount)
WHERE a.status = 'closed'
) AS total_closed
FROM transactions AS a
LEFT JOIN users AS u ON u.userid = a.userid
GROUP BY u.name
ORDER BY u.name ASC;
谢谢您的帮助!