GROUP BY上的SQL COUNT

时间:2014-04-13 00:25:39

标签: mysql sql

这是我到目前为止的代码

SELECT users_ID,Problem_ID 
FROM 'submission'
WHERE Status = "AC" 
GROUP BY users_ID,Problem_ID 

我得到了这些结果

+----------+------------+
| Users_ID | Problem_ID |
+----------+------------+
|        1 |          1 |
|        1 |          2 |
|        1 |          3 |
|        2 |          1 |
|        2 |          3 |
+----------+------------+

我只想

+----------+------------+
| Users_ID | Problem_ID |
+----------+------------+
|        1 |          3 | --  so because there are 3 results for user_ID 1
|        2 |          2 | -- and there are 2 results for user_ID 2
+----------+------------+

所以Problem_ID是我从每个用户的查询中获得的行数 但是我该如何做到这一点?

编辑:

我忘了提到该表包含相同问题的副本。例如 我得到Problem ID 1,然后在数据库中可能有两行具有相同的用户且状态为"AC"但我想只得到其中之一。

3 个答案:

答案 0 :(得分:1)

 SELECT users_ID, count(Problem_ID) as `problem_count`
 FROM `submission`
 WHERE Status = 'AC' 
 GROUP BY users_ID;

答案 1 :(得分:0)

您可以这样做:

SELECT 
    s.users_ID
    ,count(s.Problem_ID)+CASE WHEN IFNULL(userDupli.nbrUserAC, 0) > 0 THEN 1 ELSE 0 END as `problem_count`
FROM 
    `submission` s
    left join (SELECT 
                   users_ID
                   ,count(*) as nbrUserAC 
               FROM `submission` 
               WHERE Status = 'AC' 
               GROUP BY users_ID) userDupli
        on userDupli.users_ID = s.users_ID
WHERE 
    Status <> 'AC' 
GROUP BY 
    users_ID
    ,userDupli.nbrUserAC

答案 2 :(得分:0)

这应该有效:

SELECT users_ID, COUNT(DISTINCT Problem_ID)
FROM `submission`
WHERE Status = 'AC' 
GROUP BY users_ID