这将为您提供两个计数 per ip
,一个用于code
具有值 1、2 或 3 的行,另一个用于所有其余的计数(除 1、2、3 之外的所有行,包括NULL
.)
SELECT ip,
COUNT(CASE WHEN code IN (1, 2, 3) THEN 1 ELSE NULL END) AS cnt_in,
COUNT(CASE WHEN code IN (1, 2, 3) THEN NULL ELSE 1 END) AS cnt_rest
FROM parser
GROUP BY ip
ORDER BY cnt_in DESC ;
这将为您提供 3 个计数,一个用于 1、2、3,另一个用于其余整数值,第三个用于具有NULL
in的行code
:
SELECT ip,
COUNT(CASE WHEN code IN (1, 2, 3) THEN 1 END) AS cnt_in,
COUNT(CASE WHEN code NOT IN (1, 2, 3) THEN 1 END) AS cnt_not_in,
COUNT(CASE WHEN code IS NULL THEN 1 END) AS cnt_null
FROM parser
GROUP BY ip
ORDER BY cnt_in DESC ;
如果您想将第一个结果(作为您的代码)限制在前 10 行,将第二个结果限制在其他前 10 行,您可以使用两个子查询和一个UNION
:
( SELECT ip,
COUNT(*) AS cnt,
'in' AS type
FROM parser
WHERE code IN (1, 2, 3)
GROUP BY ip
ORDER BY cnt DESC
LIMIT 10
)
UNION ALL
( SELECT ip,
COUNT(*) AS cnt,
'not in' AS type
FROM parser
WHERE code NOT IN (1, 2, 3)
GROUP BY ip
ORDER BY cnt DESC
LIMIT 10
) ;
在SQL-Fiddle测试