简体   繁体   English

对 sql 查询的结果求和

[英]SUM the results of a sql query

I am trying to sum the results of the following sql code.我试图总结以下 sql 代码的结果。

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您必须 GROUP BY 然后您可以对金额求和,使用 GROUP BY 的查询中的每个列都必须在 GROUP BY 中或具有聚合 FUNCTION

so that mysql knows which date for example to get in this case the last entry date以便 mysql 知道例如在这种情况下获取最后进入日期的日期

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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