【问题标题】:SQL Server Management Studio: Return Rows in View1 that Don't Join View2SQL Server Management Studio:返回 View1 中不加入 View2 的行
【发布时间】:2017-02-16 20:42:16
【问题描述】:

我正在使用以下脚本连接两个视图,以便计算从 view2 落入 view1 的行事件数。但是,我还想查看 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 个“NumLC”的生产事件?

【问题讨论】:

  • @a_horse_with_no_name SSMS
  • 使用左连接而不是内连接,并检查右侧是否为空,例如select * from table1 t1 left join table2 t2 on t1.id = t2.fk_id where t2.fk_id is null

标签: sql sql-server join view


【解决方案1】:

使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多