MYSQL QUERY // COUNT中的问题

时间:2016-02-12 10:24:04

标签: mysql pivot

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

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,

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

你有什么建议?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以使用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