mysql - SQL根据条件合并两个表

标签 mysql sql sql-server-2008

我有两个 View ,其结果将如下所示获取

select * from CMDowntimes
select * from PMDowntimes

两个 View 的结果均显示在图像中。除最后一列外,所有列名称均相同 对于 q 结果 Ser,最后一个列名称是“CMDownTime”,对于另一个“PMDowntime”

现在我想合并这两个表,如图所示 即,如果两个 View 中都存在相同的 id,则结果中应该是单行,并且两列均为“PM_Downtime”和“CM_DownTime” 如果数据来自单个表[ View ],则另一个表应为零(如果仅存在 CM_Downtime,则 PM_Downtime 应为零)

等待快速回复 提前致谢

ID Rgn  Ter   StartDate                  EndDate                    CreatedDate  CM_Downtime
13  8   14    2014-10-24 00:30:00.000    2014-10-31 01:00:00.000    2014-10-15   10110
14  6   7     2014-10-01 09:39:00.000    2014-10-03 00:30:00.000    2014-10-26   2331
15  8   14    2014-10-01 09:54:00.000    2014-10-29 09:54:00.000    2014-10-26   40320

ID Rgn  Ter   StartDate                  EndDate                    CreatedDate  PM_Downtime
14  6   7     2014-10-01 09:39:00.000    2014-10-03 00:30:00.000    2014-10-26   2331
16  8   14    2014-10-17 09:57:00.000    2014-10-24 09:57:00.000    2014-10-26   10080


ID Rgn  Ter   StartDate                  EndDate                    CreatedDate  CM_Downtime   PM_Downtime
13  8   14    2014-10-24 00:30:00.000    2014-10-31 01:00:00.000    2014-10-15   10110         0
14  6   7     2014-10-01 09:39:00.000    2014-10-03 00:30:00.000    2014-10-26   2331          2331
15  8   14    2014-10-01 09:54:00.000    2014-10-29 09:54:00.000    2014-10-26   40320         0
16  8   14    2014-10-17 09:57:00.000    2014-10-24 09:57:00.000    2014-10-26   0             10080  

最佳答案

这本质上是一个完全外部连接。您可以在 SQL Server 或 MySQL 中使用带有聚合的 union all 来执行此操作:

select id, rgn, terr, StartDate, EndDate, CreatedDate,
       max(CM_DownTime) as CM_DownTime, max(PM_DownTime) as PM_DownTime
from (select ID, Rgn, Ter, StartDate, EndDate, CreatedDate, CM_Downtime, 0 as PM_DownTime
      from CMDowntimes
      union all
      select ID, Rgn, Ter, StartDate, EndDate, CreatedDate, 0 as CM_Downtime, PM_DownTime
      from PMDownTimes
     ) dt
group by id, rgn, terr, StartDate, EndDate, CreatedDate;

SQL Server 支持完全外连接。在该数据库中,这可能会满足您的要求:

select coalesce(c.id, p.id) as id, coalesce(c.rgn, p.rgn) as rgn, coalesce(c.terr, p.terr) as terr,
       coalesce(c.StartDate, p.StartDate) as StartDate, coalesce(c.EndDate, p.EndDate) as EndDate,
       coalesce(c.CreatedDate, p.CreatedDate) as CreatedDate,
       coalesce(c.CM_Downtime, 0) as CM_Downtime,
       coalesce(p.PM_Downtime, 0) as PM_Downtime
from CMDownTimes c full outer join
     PMDownTimes p
     on c.id = p.id;

关于mysql - SQL根据条件合并两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26572854/

相关文章:

java.sql.SQLException : Field 'supplier_id' doesn't have a default value

sql - EXEC sp_who2 - LastBatch?

MYSQL根据3列去除重复行

c# - 如何创建一个 c# 程序集以加载到 sql server 2008

sql - SQL中连续行的差异

php 循环 mysql 帮助

mysql - 错误 1364 : 1364: Field 'ssl_cipher' doesn't have a default value

MySQL: `GROUP BY` 不包括某些相等的列

mysql - INSERT INTO 从 select 语句中删除 mysql 中的一个字段

sql - NHibernate Linq 中前 5 个元素的总和