首页 > 解决方案 > 具有 HAVING 和 ORDER BY 的 Sqlite3 GROUPBY 不起作用

问题描述

我有一个 SQL 查询,它正在计算正确的输出,甚至按正确的顺序执行,但是它没有执行 having 子句。难道我做错了什么?它根本没有过滤百分比。

select table1.name as theme, 
  printf("%.2f", cast(count(table2.name)as float)/(select count(table2.name) 
  from table1
  join table2
  where table1.id = table2.theme_id)*100) as percentage from table1
join table2
where table1.id = table2.theme_id
  group by table1.id
  having percentage >=5.00
  order by percentage desc;

标签: sqlitegroup-byhaving-clausenested-query

解决方案


问题是,由于printf()返回一个字符串,计算的列percentage是一个字符串,你将它与5.00哪个数字进行比较。
这种比较不能给你你所期望的,因为它不是数字之间的比较。
解决此问题的一种方法是删除printf()并使用round()which 返回一个数字:

select table1.name as theme, 
  round(cast(count(table2.name)as float)/(select count(table2.name) 
  from table1
  join table2
  where table1.id = table2.theme_id)*100, 2) as percentage from table1
join table2
where table1.id = table2.theme_id
  group by table1.id
  having percentage >=5.00
  order by percentage desc;

percentage转换为float

having cast(percentage as float) >= 5.00

推荐阅读