如果存在于另一个表中,则选择列值,其他vise在sql server

时间:2016-01-19 10:49:09

标签: sql sql-server-2008

JobMaster

JobID   |  PLID  |  SetupTime  |
|1      |    1    |     10     |
|2      |    2    |     20     |
|2      |    3    |            |
|3      |    1    |     05     |
|3      |    3    |     12     |

OpertaionMaster

|PLID | SetupTime              |
|  1  |   12                   |
|  2  |   15                   |
|  3  |   20                   | 

Outupt包含

表JobMaster

JobID  |   Productivity  |
|1     |     12     |
|2     |     15     |
|3     |     32     |

如果JobMaster中的SetupTime,则需要在OperationMaster中添加设置时间 如果不存在,那么它应该忽略setupTime值

请帮帮我

提前谢谢

2 个答案:

答案 0 :(得分:0)

这不是一个简单的INNER JOINWHERE jm.SetupTime IS NOT NULL吗?

SELECT jm.JobID, jm.SetupTime AS Productivity 
FROM JobMaster jm 
INNER JOIN OpertaionMaster om
    ON jm.PLID = om.PLID 
WHERE jm.SetupTime IS NOT NULL

答案 1 :(得分:0)

Join将两个表放在一起,为每个jobid执行GROUP BY和SUM:

select j.jobid, sum(o.SetupTime)
from JobMaster as j
  join OpertaionMaster as o on j.PLID = o.PLID
group by j.jobid

如果您还想在没有任何时间的情况下返回jobid,请执行LEFT JOIN而不是JOIN