MYSQL QUERY // 有 COUNT 个问题

MYSQL QUERY // issue in a COUNT

我有一个按国家/地区汇总活跃客户的查询

SELECT  t1.Date,t2.country, sum(t1.countplayer) as PlayerCount
FROM
(SELECT Customers AS Player,
    Date,
    1 as countplayer
    FROM Online_customer_activity_v2
    ) t1
JOIN `players` t2
ON t1.`Player` = t2.`username`
GROUP BY t1.Date,t2.country
LIMIT 20;


+------------+--------------+-------------+
| Date       | country      | PlayerCount |
+------------+--------------+-------------+
| 2014-06-15 | Kuwait       | 1           |
| 2014-06-21 | Kuwait       | 1           |
| 2014-06-23 | Kuwait       | 1           |
| 2014-10-10 | Kuwait       | 1           |
| 2014-10-11 | Kuwait       | 1           |
| 2014-10-12 | Jordan       | 1           |
| 2014-10-13 | Jordan       | 1           |
| 2014-10-13 | Saudi Arabia | 1           |
| 2014-10-14 | Jordan       | 1           |
| 2014-10-14 | Saudi Arabia | 1           |
| 2014-10-15 | Jordan       | 1           |
| 2014-10-15 | Latvia       | 1           |
| 2014-10-15 | Saudi Arabia | 1           |
| 2014-10-16 | Jordan       | 1           |
| 2014-10-16 | Kuwait       | 1           |
| 2014-10-16 | Latvia       | 1           |
| 2014-10-16 | Saudi Arabia | 1           |
| 2014-10-17 | Jordan       | 1           |
| 2014-10-17 | Kuwait       | 1           |
| 2014-10-17 | Russia       | 1           |
+------------+--------------+-------------+

我想将此查询与有限数量的国家/地区关联起来,然后转到:

                Saudi Arabia    Kuwait     Other
2014-06-15                  3        4         0
2014-06-21                  2        4         0
2014-06-23                  1        5         0
2014-10-10                  0        6         3

我尝试添加

sum(if(t2.country = 'Saudi Arabia', sum(t1.countplayer),0)) as SaudiArabia,

如一些教程中所述,但我收到错误...(组函数的使用无效)。

你有什么建议?

您在 sum() 中的语法不正确,您甚至不需要子查询:

SELECT  t1.Date,
        sum(if(t2.country = 'Saudi Arabia', 1,0)) as SaudiArabia
FROM Online_customer_activity_v2 t1

JOIN `players` t2
ON t1.Customers = t2.`username`
GROUP BY t1.Date

您可以使用 casesum 等;

SELECT  
    t1.Date, 
    sum(case when t2.country = 'Saudi Arabia' then 1 else 0 end) `Saudi Arabia`,
    sum(case when t2.country = 'Kuwait' then 1 else 0 end) `Kuwait`,
    sum(case when t2.country in ('Saudi Arabia', 'Kuwait') then 0 else 1 end) others
FROM Online_customer_activity_v2 t1
JOIN `players` t2
ON t1.`Customers` = t2.`username`
GROUP BY t1.Date

您可以使用if,例如

SELECT  
    t1.Date, 
    sum(if(t2.country = 'Saudi Arabia', 1, 0)) `Saudi Arabia`,
    sum(if(t2.country = 'Kuwait', 1, 0)) `Kuwait`,
    sum(if(t2.country in ('Saudi Arabia', 'Kuwait'), 0, 1)) others
FROM Online_customer_activity_v2 t1
JOIN `players` t2
ON t1.`Customers` = t2.`username`
GROUP BY t1.Date