计数包含具有特定属性的元素的组

时间:2015-07-13 13:06:01

标签: sql sqlite

我有一个包含3个值的表

CREATE TABLE x (
start      integer NOT NULL,
end        integer NOT NULL,
random     integer NOT NULL);

我想计算包含至少一个元素GROUP BY start,end但是大于一个元素的组(random > 42)的数量。但据我所知HAVING只能用于聚合函数。

我目前的尝试:

SELECT count(*) FROM (
SELECT count(*) FROM routes 
GROUP BY start,end 
HAVING random > 42 
AND count(*) > 1);

结果

  

没有这样的专栏:随意

解决此问题的最有效方法是什么?

2 个答案:

答案 0 :(得分:2)

SELECT count(*)
 FROM (SELECT SUM(case when random > 42 then 1 else 0 end) as cnt 
       FROM routes  
       GROUP BY start,end
       HAVING count(*) > 1) as t
WHERE cnt > 1

答案 1 :(得分:0)

在聚合函数本身中包含条件,如下所示

SELECT count(case when random > 42 then 1 else 0 end) as computed_column
FROM routes 
GROUP BY start, end;

您的查询有点奇怪,可以重写为

SELECT COUNT(*) FROM
(
SELECT count(*) as Count_Route
FROM routes 
WHERE random > 42 
GROUP BY start, end 
HAVING count(*) > 1
) XXX;