如何合并两个select mysql查询的结果[重复]
Posted
技术标签:
【中文标题】如何合并两个select mysql查询的结果[重复]【英文标题】:How to merge the result of two select mysql query [duplicate] 【发布时间】:2021-11-09 12:58:47 【问题描述】:我的第一个查询是
select GEAR,count(GEAR)
from new_failure
where STN_CODE = "BVH" group by(Gear);
它的结果是
图片不可见时的结果
# GEAR Total
SIGNAL 8
POINT 16
HASSDAC 5
,SIGNAL 1
SSDAC 1
TRACK CIRCUIT 9
UFSBI 2
DC 1
第二次查询
select GEAR,count(GEAR)
from new_failure
where STN_CODE = "BVH"
and MONTH(fail_time) = 4
group by(Gear);
结果
# GEAR April
SIGNAL 3
POINT 4
HASSDAC 1
,SIGNAL 1
SSDAC 1
我希望结果如下图所示
【问题讨论】:
请查看***.com/questions/10538539/… select t1.Gear, t1.[This],COALESCE(t2.[April],0) AS [ April] from (select GEAR,count(GEAR) as "This" from new_failure where STN_CODE = "BVH" group by(Gear)) t1 LEFT JOIN (select GEAR,count(GEAR) as "April" from new_failure 其中STN_CODE = "BVH" and MONTH(fail_time) = 4 group by(Gear)) t2 on (t1 .Gear = t2.Gear);我的查询看起来像这样,但在 t1 出现错误。[this] "[" is not valid 【参考方案1】:您可以使用 LEFT JOIN、RIGHT JOIN 或 JOIN,具体取决于您的目标是什么,
SELECT *
FROM ( select GEAR,count(GEAR)
from new_failure
where STN_CODE = "BVH" group by(Gear) AS A
JOIN ( select GEAR,count(GEAR)
from new_failure
where STN_CODE = "BVH"
and MONTH(fail_time) = 4 AS B
ON A.orders_id=B.orders_id
或者您可以参考此链接了解类似问题 joining two select statements
【讨论】:
此解决方案不必要地过于复杂,因为两个查询都从同一个表中选择数据并按同一字段分组。唯一的区别是要计算什么,这可以通过条件计数来完成。表上的单次传递,没有连接。以上是关于如何合并两个select mysql查询的结果[重复]的主要内容,如果未能解决你的问题,请参考以下文章