我有一个包含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);
结果
没有这样的专栏:随意
解决此问题的最有效方法是什么?
答案 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;