1

I've 2 tables:

Teams:

|-- id -- username --|
|__ 1  __ user1    __|
|__ 2  __ user2    __|
|__ 3  __ user3    __|

Payments:

|-- id -- user_id -- amount --|
|__ 1  __ 1       __ 1000   --|
|__ 2  __ 1       __ 5000   --|
|__ 3  __ 2       __ 3000   --|
|__ 4  __ 1       __ 4500   --|
|__ 5  __ 2       __ 1000   --|

I want to get users total payments. in single query. result like this:

|-- user_id -- username -- total_payment --|
|__ 1       __ user1    __ 10500         --|
|__ 2       __ user2    __ 4000          --|

Thanks.

4

2 回答 2

3

If you only want the user_id without username, there is no need for a join at all since the grouping need only happen against the user_id in Payments.

SELECT 
  user_id, 
  SUM(amount) AS total
FROM Payments
GROUP BY user_id

Edit: The question has since been edited to include the username in output, so use the query below -- a join is necessary.

If you want to join in the username, it is a simple addition to the FROM and GROUP BY clauses.

SELECT 
  Teams.user_id, 
  username,
  SUM(amount) AS total
FROM 
  Teams
  /* LEFT JOIN used in case a user has no payments -- will still show in the list */ 
  LEFT JOIN Payments ON Teams.user_id = Payments.user_id
GROUP BY 
  Teams.user_id, 
  Teams.username
于 2012-04-23T13:57:31.880 回答
0
SELECT A.user_id,B.user_name,A.total AS total_payment
FROM
(
SELECT 
  user_id, 
  SUM(amount) AS total
FROM Payments
GROUP BY user_id
) A,
Teams B
WHERE A.user_id = B.id;
于 2012-04-23T14:02:40.973 回答