【问题标题】:How to merge the result of two select mysql query [duplicate]如何合并两个select mysql查询的结果[重复]
【发布时间】: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

我希望结果如下图所示

【问题讨论】:

  • 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

标签: mysql


【解决方案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

【讨论】:

  • 此解决方案不必要地过于复杂,因为两个查询都从同一个表中选择数据并按同一字段分组。唯一的区别是要计算什么,这可以通过条件计数来完成。表上的单次传递,没有连接。
猜你喜欢
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
  • 2017-04-05
  • 2012-03-08
  • 1970-01-01
  • 2019-06-28
相关资源
最近更新 更多