2014-01-07 68 views
3
類別

這裏是我的table計數結果通過

http://www.sqlfiddle.com/#!2/47e2d/8

╔════╦══════════╦════════╦═══════╦════════╗ 
║ id ║ category ║ userid ║ users ║ points ║ 
╠════╬══════════╬════════╬═══════╬════════╣ 
║ 1 ║ 2  ║ 91 ║ user1 ║ 100 ║ 
║ 2 ║ 3  ║ 92 ║ user2 ║ 80 ║ 
║ 3 ║ 4  ║ 93 ║ user3 ║ 10 ║ 
║ 4 ║ 4  ║ 91 ║ user1 ║ 12 ║ 
╚════╩══════════╩════════╩═══════╩════════╝ 

如何獲得每個類別中的最高分用戶的計數結果?

在上面的例子,我想

user1: 2 
user2: 1 

尋找在計算器一段時間類似的問題後,我想出了

SELECT users, COUNT(*) 
FROM `table` 
WHERE points=(SELECT MAX(points) FROM `table`) 
GROUP BY points; 

但它不會產生我想要什麼。

回答

2

試試這個:

SELECT 
    users, 
    COUNT(*) 
FROM 
    (SELECT 
    users, 
    COUNT(*) COUNT 
    FROM 
    `table` 
    WHERE points IN 
    (SELECT 
     MAX(points) 
    FROM 
     `table` 
    GROUP BY category) 
    GROUP BY points) temp 
GROUP BY users ; 
2

試試這個:

SELECT 
    t1.users, 
    COUNT(t2.category) 
FROM `table` AS t1 
INNER JOIN 
(
    SELECT category, MAX(points) MAxpoints 
    FROM `table` 
    GROUP BY category 
) AS t2 ON t1.category = t2.category AND t1.points = t2.MAxpoints 
GROUP BY t1.users; 

的加入子查詢:

SELECT category, MAX(points) MAxpoints 
    FROM `table` 
    GROUP BY category 

會給你最大points每個類別,那麼我們得到的那些用戶通過將該子查詢與原始表加入,然後我們使用COUNT爲每個用戶計算最大點的類別。

這會給你:

╔════════╦═══════╗ 
║ USERS ║ COUNT ║ 
╠════════╬═══════╣ 
║ user1 ║  2 ║ 
║ user2 ║  1 ║ 
╚════════╩═══════╝ 
2

試試這個:

SELECT users, count(*) 
FROM `TABLE`, 
    (SELECT category, max(points) as max_points FROM `TABLE` GROUP BY category) as maxes 
WHERE maxes.category = `TABLE`.category AND maxes.max_points = `TABLE`.points 
GROUP BY users 

這裏的關鍵是創建一個包含最高分,每一個臨時表類別

SELECT category, max(points) as max_points FROM `TABLE` GROUP BY category 

然後我使用它與現有的TABLE一起查找具有最高點的正確用戶。