MySQL:仅选择一些分组的行

时间:2013-05-24 11:37:03

标签: 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

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

对不起,我没有强调这样一个事实,即所有行动必须是login。因此,结果将没有john,因为有与此用户名相关的操作comment

3 个答案:

答案 0 :(得分:3)

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 ;

但我认为,(username, login)上的索引和(username, points)上的索引,这将是效率最高的:

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 ;

答案 1 :(得分:0)

您可以使用聚合和聪明的having子句来执行此操作:

select username, sum(points), count(*) 
from tbl
group by username
having sum(case when points <= 5 then 1 else 0 end) = 0 and   -- count number with points < 5
       max(action) = min(action) and  -- all the actions are the same and
       min(action) = 'login'

答案 2 :(得分:-1)

尝试此查询

select username, action, sum(points), count(*) 
from 
tbl
group by username, action 
having sum(if (points<=5, 1, 0)) =0  and count(*) >=2

SQL FIDDLE

| USERNAME | ACTION | SUM(POINTS) | COUNT(*) |
----------------------------------------------
|    peter |  login |          16 |        2 |