sqlite - 具有 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;
解决方案
问题是,由于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
推荐阅读
- iot - 如何在 IFTTTT 中为不同用户创建 DELETE 端点
- javascript - TypeError: undefined is not a function in discord.js
- amazon-web-services - 如何将 Redshift 集群附加到 VPC
- redis - 使用相同的数据目录运行多个 redis 服务器
- opencv - OpenCV:6个摄像头的汽车鸟瞰图
- java - 从 2d 矩阵创建 3d 矩阵
- c++ - 如何调试 DirectShow 推送源过滤器?
- swift - “线程 1:EXC_BAD_ACCES(代码=2,地址=0x7ffee73ceff8)”是什么意思?
- c# - Docker 和 ARM64 - 无法加载文件或程序集
- android - 无法使用选择器突出显示 RecyclerView 中的项目