简体   繁体   中英

SUM the results of a sql query

I am trying to sum the results of the following sql code.

SELECT users.username, users.cell, users.date, coin_bank.bought_coins
FROM users 
LEFT JOIN coin_bank ON users.username = coin_bank.seller
WHERE users.sponserid = '27'

The above code works, I however want to sum the bought_coins which are returning as duplicate.

I have tried sub queries I can't seem to get it right. Any help will be appreciated.

查看结果

Is this what you want?

SELECT u.username, SUM(cb.bought_coins)
FROM users u LEFT JOIN
     coin_bank cb
     ON u.username = cb.seller
WHERE u.sponserid = '27'
GROUP BY u.username;

You have to GROUP BY and then you can SUM the amount, EvERY column in a query with GROUP BY has to be in the GROUP BY or have a Aggregation FUNCTION

so that mysql knows which date for example to get in this case the last entry date

SELECT users.username,
       users.cell,
       MAX(users.date),
       SUM(coin_bank.bought_coins)
FROM users
LEFT JOIN coin_bank ON users.username=coin_bank.seller
WHERE users.sponserid = '27'
GROUP BY users.username,
         users.cell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM