2016-02-12 99 views
3

我有一個查詢由國家MySQL查詢//在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, 

正如一些教程描述,但我得到一個錯誤......(無效使用組功能)。

你有什麼建議?

回答

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 
0

總和()在你的語法不正確,你甚至不需要子查詢:

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