我可以使用哪种类型的连接来重现这些结果

时间:2009-12-21 19:51:13

标签: sql tsql join

我有以下包含此数据的视图

ActivityRecId RegionRecId IsExcluded
1             null        1
2             null        1
3             1           1
3             2           1
4             1           1
5             null        0

我想要做的是将区域表加入上面的视图以获取以下记录。

ActivityRecId RegionRecId IsExcluded
1             null        1
2             null        1
3             1           1
3             2           1
3             3           0
3             4           0
4             1           1
4             2           0
4             3           0
4             4           0
5             null        0

区域表格包含以下列:

  • RegionRecId
  • RegionName

任何建议。如果您需要任何其他信息,请与我们联系。

--------------------- CORRECT QUESTION ------------------------
ActivityRecId RegionRecId IsExcluded
    1             null        1
    2             null        1
    3             1           1
    3             2           1
    3             3           0
    3             4           0
    4             1           1
    4             2           0
    4             3           0
    4             4           0
    5             1           0
    5             2           0
    5             3           0
    5             4           0

如果它更容易,活动1和2也可以列出所有区域。

谢谢,

2 个答案:

答案 0 :(得分:0)

Here很好地参考了看联接。我认为你需要一个左外连接

答案 1 :(得分:0)

我没有一个SQL Server方便测试这个,但是会像

那样
select  *
from    myView

union

select  myView.ActivityRecId,
        region.RegionRecId,
        0 as IsExcluded
from    myView cross join region
where   (myView.RegionRecId is not null or myView.IsExcluded = 0)
        and not exists (
            select  null
            from    myView
            where   myView.RegionRecId = region.RegionRecId
        )

是你想要的吗?

相关问题