SQL根据条件合并两个表

时间:2014-10-26 12:14:07

标签: mysql sql sql-server-2008

我有两个视图,结果将被提取,如下所示

select * from CMDowntimes
select * from PMDowntimes

两个视图的结果显示在image.all列名称相同,但最后一列除外 对于q结果,ser的最后一列名称是“CMDownTime”,另一列是“PMDowntime”

现在我想合并这两个表,如图所示 即如果两个视图中都存在相同的id,则结果应为单行“PM_Downtime”和“CM_DownTime” 如果数据来自单个表[view],则其他的shud为零(如果只有CM_Downtime存在,则PM_Downtime应为Zer0)

等待快速反应 Thanx提前

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  

2 个答案:

答案 0 :(得分:1)

这基本上是full outer join。您可以使用带有聚合的union all在SQL Server或MySQL中执行此操作:

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支持full outer join。在该数据库中,这可能是您想要的:

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;

答案 1 :(得分:0)

SELECT    A.ID,
          A.Rgn,
          A.StartDate,
          A.EndDate,
          A.CreatedDate,
          IsNull(A.CM_Downtime, 0),
          IsNull(B.PM_Downtime, 0)
FROM      Table1 A
LEFT JOIN Table2 B ON a.ID = B.ID
UNION
SELECT    A.ID,
          A.Rgn,
          A.StartDate,
          A.EndDate,
          A.CreatedDate,
          IsNull(B.CM_Downtime, 0),
          IsNull(A.PM_Downtime, 0)
FROM      Table2 A
LEFT JOIN Table1 B ON a.ID = B.ID