SQLite中骨料的误用

SQLite中骨料的误用,sql,sqlite,group-by,aggregate-functions,having-clause,Sql,Sqlite,Group By,Aggregate Functions,Having Clause,此SQLite查询中出现此错误: select f.rid, c.title, sum(some_expression) as ratio from doesntmatter where c.active = 1 or (ratio = 1.0 and c.active = 0 and c.deactivated in (1, 2, 3, 4, 5) group by f.rid 问题通过具有子句来解决: select f.rid, c.title, sum(some_expres

SQLite
查询中出现此错误:

select f.rid, c.title, sum(some_expression) as ratio
from doesntmatter
where c.active = 1 or (ratio = 1.0 and c.active = 0
      and c.deactivated in (1, 2, 3, 4, 5)
group by f.rid
问题通过
具有
子句来解决:

select f.rid, c.title, sum(some_expression) as ratio
from doesntmatter
where c.active = 1 or (c.active = 0
      and c.deactivated in (1, 2, 3, 4, 5)
group by f.rid
having ratio = 1.0

但在我的例子中,这改变了表达式的语义。您知道如何实现原始
where
子句中的表达式吗?

基本上,您不能在where子句中引用别名列。看看这个,看看如何解决这个问题

另外,您应该通过
select
语句中的所有非聚合列添加到组中,在本例中,
c.id
c.title

很难为您重写该查询,因为逻辑有点难以理解(因为GROUPBY错误)

编辑:

再想一想,您可能只需要更正
分组依据

select c.id, c.title, sum(some_expression) as ratio
from doesntmatter
where c.active = 1 or (c.active = 0 and c.deactivated in (1, 2, 3, 4, 5))
group by c.id, c.title
having ratio = 1.0
或者可能:

select f.rid, sum(some_expression) as ratio
from doesntmatter
where c.active = 1 or (c.active = 0 and c.deactivated in (1, 2, 3, 4, 5))
group by f.rid
having ratio = 1.0

我无法帮助您完成上一部分,因为我不知道字段和表的数据,也不知道如何解释它们。但是选择组中不存在的字段是个坏主意。无论如何,请记住,您始终可以连接回原始表并获取您要查找的信息,而不仅仅是
选择中显示的字段

@MostyMostacho谢谢,我会尝试。我尝试过,但无法移动
求和(某些表达式)
to
where子句
因为有两个聚合函数-
sum
count
可以创建嵌套查询吗?内部查询将创建一个表(id、title、active、deactivated、ratio),外部查询将仅选择满足
的行,其中c.active=1或(ratio=1.0,c.active=0,c.deactivated in(1、2、3、4、5)
。但是我不知道如何引用外部查询中的列……我注意到您正在解决另一个问题中的嵌套语句。我只是害怕
MySQL
分组方式
是可以的。有两个联接表。我将尝试使用
嵌套查询
,但似乎我只有
的可能性完整扫描
如您在另一个问题中所写。我已更新了该问题。可能它只需要对分组依据进行更正。如果这仍然需要更多处理,则可能会使用子查询。注意:分组依据不正确