内部联接值存在或不存在时的SQL查询

时间:2019-07-03 02:20:29

标签: sql sql-server

我有以下查询:

select 
    case when jp.IntValue = 0 then 'N' else 'Y' end 'Enabled',
    j.LastChange 'Last Changed',
    90 'Lookback History Days',
    max(h.StartTime) 'Last Run',
    j.JobName 'Job Name' 
from 
    Job j
inner join 
    JobProperty jp on jp.JobId = j.JobId and jp.PropertyId = 397
inner join 
    History h on h.JobId = j.JobId
group by 
    jp.IntValue, j.LastChange, j.JobName

我想做的就是像这样扩展它:

select  
    case when (jp.IntValue = 0 or jp.IntValue not exists) then 'N' else 'Y' end 'Enabled',
    j.LastChange 'Last Changed',
    90 'Lookback History Days',
    max(h.StartTime) 'Last Run',
    j.JobName 'Job Name' 
from 
    Job j
full outer join 
    JobProperty jp on jp.JobId = j.JobId and jp.PropertyId = 397
inner join 
    History h on h.JobId = j.JobId
group by 
    jp.IntValue, j.LastChange, j.JobName

但我似乎无法使其正常工作。

基本上我想加入表格,但是如果表格不能在FK上加入,我仍要记下工作。

1 个答案:

答案 0 :(得分:1)

如果您需要所有作业,请使用left join

select (case when jp.IntValue = 0 or jp.IntValue not exists) then 'N' else 'Y'
        end) as Enabled,
       j.LastChange as LastChanged,
       90 as LookbackHistoryDays,
       max(h.StartTime) as LastRun,
       j.JobName
from Job j left join
     JobProperty jp
     on jp.JobId = j.JobId and
        jp.PropertyId = 397 left join
     History h
     on h.JobId = j.JobId
group by (case when jp.IntValue = 0 or jp.IntValue not exists) then 'N' else 'Y'
          end), j.LastChange, j.JobName