2017-02-16 27 views
0

我正在使用以下腳本來加入兩個視圖,以便我可以將來自view2的行事件數落入視圖1。但是,我還想看到view1中的行事件在其下沒有任何view2行事件。SQL Server Management Studio:返回View1中的行,但不加入View2

腳本:

Select vp.id, vp.EventName, vp.Unit, vp.Product, vp.StartTime, vp.EndTime, vp.Production, vp.BDP, count(distinct vl.Name) as NumLCs 
from [V_ProductionEvents] vp 
join [V_LossEvents] vl on vl.Unit = vp.Unit and vl.StartTime >= vp.StartTime and vl.EndTime <= vp.EndTime 
where vp.StartTime > '2/01/2017' 
group by vp.id, vp.Unit, vp.StartTime, vp.EndTime, vp.EventName, vp.Product, vp.bdp, vp.Production 
order by vp.StartTime desc 

對於距離生產事件開始每丟失事件/結束時間,NumLC + = 1 ...有誰知道我可以查看有0「NumLCs更多的生產活動「?

+0

@a_horse_with_no_name SSMS – Dplusa25

+0

使用左連接,而不是內部的連接,並檢查右側爲空,例如'select * from table1 t1 left join table2 t2 on t1.id = t2.fk_id where t2.fk_id is null' – AndrewP

回答

0

使用left join

select 
    vp.id 
    , vp.EventName 
    , vp.Unit 
    , vp.Product 
    , vp.StartTime 
    , vp.EndTime 
    , vp.Production 
    , vp.BDP 
    , NumLCs = count(distinct vl.Name) 
from [V_ProductionEvents] vp 
    left join [V_LossEvents] vl 
    on vl.Unit = vp.Unit 
    and vl.StartTime >= vp.StartTime 
    and vl.EndTime <= vp.EndTime 
where vp.StartTime > '2/01/2017' 
group by 
    vp.id 
    , vp.Unit 
    , vp.StartTime 
    , vp.EndTime 
    , vp.EventName 
    , vp.Product 
    , vp.bdp 
    , vp.Production 
order by vp.StartTime desc 
相關問題