我想知道如何按照包含select count()
和count()
语句的字段进行分组。我知道我们必须将所有选择字段放在group by中,但由于字段中的第二个count()
语句,它不会让我这样做。
create table C as(
select a.id, a.date_id,
(select count(b.hits)*1.00 where b.hits >= '9')/count(b.hits) AS percent **<--error here
from A a join B b
on a.id = b.id
group by 1,2,3) with no data primary index(id);
这是我的错误:
[SQLState HY000] GROUP BY and WITH...BY clauses may not contain
aggregate functions. Error Code: 3625
当我在第三行中添加第二个计数时,只得到1或0,这是不正确的。
`((select count(b.hits)*1.00 where b.hits >= '9')/(select count(b.hits))) AS` percent
我是否需要进行自我加入,或者我有什么方法可以使用嵌套查询?
答案 0 :(得分:1)
您需要修复group by
。但是,您可以将查询简化为:
create table C as
select a.id, a.date_id,
avg(b.hits >= 9) as percent
from A a join
B b
on a.id = b.id
group by a.id, a.date_id
with no data primary index(id);
答案 1 :(得分:0)
看起来您只需要分组2列,而不是3列,另外您不需要进行子选择:
create table C as(
select a.id, a.date_id,
SUM(CASE WHEN b.hits >= '9' THEN 1 ELSE 0 END)/COUNT(b.hits) AS percent
from A a join B b
on a.id = b.id
group by 1,2) with no data primary index(id);