SQL查询内部连接
问题描述:
我正在使用SQL Server 2008 R2。 我有两个表让我们说TblGroup
和TblComplatedDetails
。SQL查询内部连接
TblGroup包含组的名称以及MemberId
和GroupType (i.e. in Daily, Weekly, Start, End)
和TblComplatedDetails
包含GroupId (i.e. foreign key of TblGroup)
以及完成的日期时间。 现在我想要除GroupType="End"
以外的所有特定组MemberId
以及只有在“TblCompletedDetails”中没有记录的“开始”类型的组。因此,记录集是类似下面的东西:
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
所以对于成员Id = 1个所需的组可以是:
=======
GroupId
=======
1
4
但对于成员Id = 2所需resule是:
=======
GroupId
=======
2
6
7
因为7是在TblCompletedDetails中没有外键的组的“开始”类型。 任何人都可以有想法吗?等待您的宝贵回应。
答
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)
)
条件,你可能需要使用** TblGroup GRP ** 1 ** grp.GroupType不在( '终结')** 2 ** grp.GroupType = '开始' 和(选择从TblCompletedDetails计数(*)tcd其中grp.GroupId = tcd.GroupId)** – 2012-07-18 09:28:46
@NaveenBabu在这种情况下,我只会得到只有“开始”类型的组的记录。除了类型“结束”和组的“开始”类型之外,我想要所有类型的组不能有TblCompledDetails中的记录。 – Dev 2012-07-18 09:45:42