MySQL:仅选择一些分组的行

我有以下数据库(小例子):

ID | username | action  | points
1  | matt     | login   | 3
2  | john     | comment | 6
3  | john     | login   | 6
4  | peter    | login   | 8
5  | peter    | login   | 8

而且我不确定如何选择和分组具有相同操作(=登录)和高于5的用户名(对于所有操作).

预期成绩:

username | COUNT | points(SUM)
peter    | 2     | 16

我尝试了子查询,但找不到合适的解决方案.你知道怎么做吗?非常感谢您的帮助!

对不起,我没有强调这一事实,即所有操作都必须登录.因此,结果将没有john,因为有与此用户名相关的操作注释.

最佳答案

SELECT    username, COUNT(*) AS cnt, SUM(points) AS points
FROM      tableX AS t
GROUP BY  username
HAVING    COUNT(*) = COUNT(CASE WHEN action = 'login' THEN action END) 
   AND    SUM(points) > 5 ;

要么:

SELECT    username, COUNT(*) AS cnt, SUM(points) AS points
FROM      tableX AS t
WHERE     action = 'login'
  AND     NOT EXISTS
            ( SELECT    *
              FROM      tableX AS tt
              WHERE     tt.username = t.username
                AND     ( tt.action <> 'login' OR tt.action IS NULL )
            )
GROUP BY  username
HAVING    SUM(points) > 5 ;

但我认为,通过索引(用户名,登录名)和一个(用户名,点数),这将是最有效的:

SELECT    username, COUNT(*) AS cnt, SUM(points) AS points
FROM      tableX AS t
GROUP BY  username
HAVING    MIN(action) = 'login'
   AND    MAX(action) = 'login' 
   AND    SUM(points) > 5 ;
点赞