带有 HAVING 和 ORDER BY 的 Sqlite3 GROUPBY 不起作用
Sqlite3 GROUPBY with HAVING and ORDER BY not working
我有一个 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;
问题在于,由于 printf()
returns 是一个字符串,因此计算出的列 percentage
是一个字符串,您将它与 5.00
进行比较,后者是一个数字。
这种比较不能给你你所期望的,因为它不是数字之间的比较。
解决这个问题的一种方法是删除 printf()
并使用 round()
代替 returns 一个数字:
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
我有一个 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;
问题在于,由于 printf()
returns 是一个字符串,因此计算出的列 percentage
是一个字符串,您将它与 5.00
进行比较,后者是一个数字。
这种比较不能给你你所期望的,因为它不是数字之间的比较。
解决这个问题的一种方法是删除 printf()
并使用 round()
代替 returns 一个数字:
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