mysql - 多个选择语句在mysql中给出错误的输出
问题描述
我正在尝试执行一个多选语句查询,如下所示,
select Date(Transactiondate),
(Select count(*) from tms_plaza.tms_lanetrans where vehiclecatcode='cat1' and transactiondate >= '2018-05-01' and transactiondate <= '2018-07-01') as LMV,
(Select count(*) from tms_plaza.tms_lanetrans where vehiclecatcode='cat2' and transactiondate >= '2018-05-01' and transactiondate <= '2018-07-01' ) as LCV,
(Select count(*) from tms_plaza.tms_lanetrans where vehiclecatcode='cat3' and transactiondate >= '2018-05-01' and transactiondate <= '2018-07-01' ) as Truck,
(Select count(*) from tms_plaza.tms_lanetrans where vehiclecatcode='cat4' and transactiondate >= '2018-05-01' and transactiondate <= '2018-07-01' ) as Bus,
(Select count(*) from tms_plaza.tms_lanetrans where vehiclecatcode='cat5' and transactiondate >= '2018-05-01' and transactiondate <= '2018-07-01' ) as MAV,
(Select count(*) from tms_plaza.tms_lanetrans where vehiclecatcode='cat6' and transactiondate >= '2018-05-01' and transactiondate <= '2018-07-01' ) as MAV6
from tms_plaza.tms_lanetrans where transactiondate >= '2018-05-01' and transactiondate <= '2018-07-01' group by date(transactiondate);
但这给出了非常错误的输出,因为对于所有日期它正在计算相同的数字,如下所示
2018-05-17 292 628 1317 165 1423 9
2018-05-17 292 628 1317 165 1423 9
2018-05-17 292 628 1317 165 1423 9
2018-05-17 292 628 1317 165 1423 9
2018-05-17 292 628 1317 165 1423 9
2018-05-17 292 628 1317 165 1423 9
2018-05-17 292 628 1317 165 1423 9
2018-05-17 292 628 1317 165 1423 9
有人可以帮我解决我在这方面做错的地方吗?
解决方案
您可以使用条件聚合来做到这一点:
select Date(Transactiondate),
sum(vehiclecatcode='cat1') as LMV,
sum(vehiclecatcode='cat2') as LCV,
sum(vehiclecatcode='cat3') as Truck,
sum(vehiclecatcode='cat4') as Bus,
sum(vehiclecatcode='cat5') as MAV,
sum(vehiclecatcode='cat6') as MAV6
from tms_plaza.tms_lanetrans
where transactiondate >= '2018-05-01' and transactiondate <= '2018-07-01'
group by date(transactiondate);
推荐阅读
- python - 编写在 Unix 和 Windows 上运行的简单 python 脚本的最佳方法是什么
- java - 如果无法实例化抽象类,为什么会出现以下情况?
- c# - 如何将 SQL 数据 + 硬编码数据添加到数据模型类以在组合框中进行绑定?
- javascript - 函数在完成 promise/await 之前返回(阻塞代码)
- c# - 解析租户连接字符串
- c# - 无法在服务器上找到请求的 .Net Framework 数据提供程序错误
- web-scraping - Find_by_xpath 结果有错误
- java - 没有找到 bean NoSuchBeanDefinitionException
- algorithm - 在numpy中的条件函数之前是否有保持值?
- python - Spark Dataframe Group By Operation 并从每组中选取 N 个值