2

これには、「name」、「trans_status」、「amount」の3つの列が含まれます。各'name'が1つの行にあり、4つのステータス(new、pending、final、closed)のそれぞれのすべての金額の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 に答える