SQL查询内部联接

时间:2012-07-18 09:07:40

标签: sql sql-server-2008

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

TblGroup包含组的名称以及MemberIdGroupType (i.e. in Daily, Weekly, Start, End)以及TblComplatedDetails包含GroupId (i.e. foreign key of TblGroup)以及完成的日期时间。 现在,只有在TblCompletedDetails中没有记录时,我才想要除MemberId和“开始”类型的组之外的所有特定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,所需的resule是:

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

因为7是TblCompletedDetails中没有外键的“Start”类型的Group。 谁能有想法?等待您的宝贵回应。

1 个答案:

答案 0 :(得分: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)
   )