我需要查询一个表才能返回行,但是我无法正确查询表。这是我的表格视图:
Id Name Date Subject TrackingToken RegardingObjectId Type TypeName
1 XXXX 8/26/2015 RE: XXXXXX CRM:0030062 496BF810-4DBE-E311-9357-00505686395E 112 RE: YYYY
1 XXXX 8/27/2015 RE: XXXXXX CRM:0030055 AA8C2F71-CDD1-E311-894A-005056863ADA 112 RE: YYYY
1 XXXX 8/28/2015 RE: XXXXXX CRM:0030055 4DF02C89-2FBE-E311-9357-00505686395E 112 RE: YYYY
1 XXXX 8/29/2015 RE: XXXXXX CRM:0030049 496BF810-4DBE-E311-9357-00505686395E 112 RE: YYYY
1 XXXX 8/30/2015 RE: XXXXXX CRM:0030049 06393EF9-71CC-E311-894A-005056863ADA 112 RE: YYYY
1 XXXX 8/31/2015 RE: XXXXXX CRM:0030047 8BE51823-52BE-E311-9357-00505686395E 112 RE: YYYY
1 XXXX 9/1/2015 RE: XXXXXX CRM:0030003 6ABE11CA-BABF-E311-89E9-005056863ADA 112 RE: YYYY
结果集应返回:
Id Name Date Subject TrackingToken RegardingObjectId Type TypeName
1 XXXX 8/27/2015 RE: XXXXXX CRM:0030055 AA8C2F71-CDD1-E311-894A-005056863ADA 112 RE: YYYY
1 XXXX 8/28/2015 RE: XXXXXX CRM:0030055 4DF02C89-2FBE-E311-9357-00505686395E 112 RE: YYYY
1 XXXX 8/29/2015 RE: XXXXXX CRM:0030049 496BF810-4DBE-E311-9357-00505686395E 112 RE: YYYY
1 XXXX 8/30/2015 RE: XXXXXX CRM:0030049 06393EF9-71CC-E311-894A-005056863ADA 112 RE: YYYY
换句话说:选择TrackingToken列重复的所有记录,AboutObjectId具有不同的值。
当前查询:
select [OwnerId],[OwnerIdName],[CreatedOn],[Subject],
[TrackingToken],[RegardingObjectId],
[RegardingObjectTypeCode],[RegardingObjectIdName]
from [TableX].[dbo].[Email] a
where not exists (select [TrackingToken], [RegardingObjectId]
from [TableX].[dbo].[Email] b
where a.[TrackingToken] = b.[TrackingToken]
and a.[RegardingObjectId] = b.[RegardingObjectId]
AND RegardingObjectTypeCode = 112
group by [TrackingToken],[RegardingObjectId]
having count(*)> 1)
and a.TrackingToken in (select TrackingToken
from [TableX].[dbo].[Email]
group by TrackingToken
having count(*) > 1)
and a.RegardingObjectId is not null
and a.RegardingObjectTypeCode = 112
and a.TrackingToken is not null
order by a.TrackingToken desc