使用SUM()和WHERE的多个select语句?

时间:2012-05-09 22:55:40

标签: mysql

这涉及三个栏目'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;

感谢您的帮助!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;