1

我有一个像这样的表(SQLite DB),

CREATE TABLE parser (ip text, user text, code text);

现在我需要按字段分组计算有多少code个值是 any 1, 2, or 3,有多少个不是。ip

但就我而言,我不能完全做到这一点,而是用两个 SQL 短语。

例如

select count(*) as cnt, ip 
from parser 
where code in (1, 2, 3) 
group by ip 
order by cnt DESC 
limit 10

和一个not in查询。

那么,我可以将两个查询合并为一个查询吗?

4

1 回答 1

1

这将为您提供两个计数 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,另一个用于其余整数值,第三个用于具有NULLin的行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测试

于 2013-08-20T06:04:00.237 回答