2

这涉及三列'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;

谢谢您的帮助!

4

2 回答 2

6
select u.name,
sum(case when status = 'new' then amount else 0 end) as total_new,
sum(case when status = 'pending' then amount else 0 end) as total_pending,
sum(case when status = 'final' then amount else 0 end) as total_final,
sum(case when status = 'closed' then amount else 0 end) as total_closed
from users as u
left join transactions as t on u.userid = t.userid
group by u.name
于 2012-05-09T23:08:55.917 回答
0

我不确定试试这个:

SELECT a.userid, u.name, 
    (SELECT SUM(amount) AS total_new FROM transactions
      WHERE status = 'new' 
    ),
    (SELECT SUM(amount) AS total_pending FROM transactions
      WHERE status = 'pending' 
    ),
    (SELECT SUM(amount) AS total_final FROM transactions
      WHERE status = 'final' 
    ),
    (SELECT SUM(amount) AS total_closed FROM transactions
      WHERE status = 'closed' 
    ) 
    FROM transactions AS a
    LEFT JOIN users AS u ON u.userid = a.userid
    GROUP BY u.name
    ORDER BY u.name ASC;
于 2012-05-09T23:05:44.397 回答