Mysql查询分组问题

时间:2016-02-12 08:43:14

标签: mysql group-by inner-join

我有以下mysql查询

    SELECT  t2.country,t1.deposits

    FROM(
    SELECT Online_customer_activity_v2.Customers AS Player,
    sum(Real_Money) as Deposits
    FROM Online_customer_activity_v2
    group by Customers 
    ) t1

    INNER JOIN

    (
        SELECT username as Player, 
        `players`.`country` as country
        FROM `players`   
    ) t2
    ON t1.`Player` = t2.`Player`

    ORDER BY t1.Deposits DESC

结果是:

+-------------------------+----------+
| country                 | deposits |
+-------------------------+----------+
| Saudi Arabia            | 773410   |
| Saudi Arabia            | 269845   |
| Kuwait                  | 132065   |
| Kuwait                  | 130245   |
| Saudi Arabia            | 114006   |
| Kuwait                  | 110920   |
| Kuwait                  | 98755    |
| Kuwait                  | 86180    |
| Kuwait                  | 86005    |
| Kuwait                  | 84545    |
| Saudi Arabia            | 71485    |
| Kuwait                  | 69247    |
| Saudi Arabia            | 65300    |
| Kuwait                  | 65000    |
| United Arab Emirates    | 63795    |
| Kuwait                  | 59935    |

现在,当我尝试按t2.country分组以按国家/地区汇总我的查询时,

SELECT  t2.country,t1.deposits
    FROM(
    SELECT Online_customer_activity_v2.Customers AS Player,
    sum(Real_Money) as Deposits
    FROM Online_customer_activity_v2
    group by Customers 
    ) t1 
    INNER JOIN
    (
        SELECT username as Player, 
        `players`.`country` as country
        FROM `players`   
    ) t2
    ON t1.`Player` = t2.`Player`
    GROUP BY t2.country
    ORDER BY t1.Deposits DESC

我得到以下内容:

+-------------------------+----------+
| country                 | deposits |
+-------------------------+----------+
| Saudi Arabia            | 65300    |
| Bahrain                 | 6850     |
| Egypt                   | 700      |

它基本上没有正确地由客户总结... 我做错了什么,我应该如何更正此查询以使其正常工作? 谢谢!

1 个答案:

答案 0 :(得分:3)

如果您希望基于sum(t1.deposits)使用t2.country sum函数获取aggregate

SELECT  t2.country, sum(t1.deposits) deposits
FROM(
    SELECT Customers AS Player,
    sum(Real_Money) as Deposits
    FROM Online_customer_activity_v2
    group by Customers 
) t1 
JOIN `players` t2
ON t1.`Player` = t2.`username`
GROUP BY t2.country
ORDER BY Sum(t1.Deposits) DESC