1

我正在研究 SQL Server 2008 R2。我有两张桌子让我们说TblGroupTblComplatedDetails

TblGroup 包含组的名称以及MemberIdGroupType (i.e. in Daily, Weekly, Start, End)TblComplatedDetails包含GroupId (i.e. foreign key of TblGroup)完成的日期时间。现在,只有在 TblCompletedDetails 中没有记录的情况下,我才想要MemberId除AND“开始”类型的组之外的所有特定组。GroupType="End"所以记录集如下所示:

TblGroup 
==================================
Id  MemberId    GroupType
==================================
1   1       Daily
2   2       Daily
3   3       Daily
4   1       Weekly
5   1       Start
6   2       Weekly 
7   2       Start 
8   2       End
9   1       End
10  1       End


TblCompletedDetails
======================================
Id  GroupId     CompletedDate
======================================
1   1       xxxxxxxxxxxxxx
2   2       xxxxxxxxxxxxxx
3   3       xxxxxxxxxxxxxx
4   4       xxxxxxxxxxxxxx
5   1       xxxxxxxxxxxxxx
6   2       xxxxxxxxxxxxxx
7   3       xxxxxxxxxxxxxx
8   5       xxxxxxxxxxxxxx
9   6       xxxxxxxxxxxxxx

因此,对于 MemberId = 1,所需的组可以是:

=======
GroupId
=======
1
4

但是对于 MemberId = 2 所需的结果是:

=======
GroupId 
=======
2
6
7

因为 7 是“开始”类型的组,在 TblCompletedDetails 中没有外键。任何人都可以有想法吗?等待您的宝贵回复。

4

1 回答 1

2
select g.ID GroupID
  from TblGroup g
 where g.MemberID = @MemberID
   and g.GroupType <> 'end'
   and
   (
       -- Row is qualified if it is not start
          g.GroupType <> 'start'
       -- Or, if it is, does not have an entry in TblCompletedDetails
       or not exists (select *
                        from TblCompletedDetails d
                       where d.GroupId = g.ID)
   )
于 2012-07-18T10:03:43.623 回答