一组记录上的SQL匹配

一组记录上的SQL匹配,sql,sql-server,sql-server-2008-r2,Sql,Sql Server,Sql Server 2008 R2,假设我有一个多对多的关系: Profile <- Profile_Attribute -> Attribute ------- ----------------- --------- ProfileID Profile_AttributeID AttributeID Name ProfileID Name AttributeID Value 我想你只是在寻找

假设我有一个多对多的关系:

Profile  <-  Profile_Attribute  -> Attribute
-------      -----------------     ---------
ProfileID    Profile_AttributeID   AttributeID
Name         ProfileID             Name
             AttributeID
             Value

我想你只是在寻找这样的东西:

select c.ProfileId, Count(*) from @tblCheck as a
inner join Profile_attribute as b on a.AttributeID = b.AttributeID and a.Value = b.Value
inner join Profile as c on c.ProfileID = b.ProfileID
Group by c.ProfileID

示例数据和预期数据可能会更好。为什么在@tblCheck中使用左外部联接而不是内部联接?是的,很好,我不知道为什么这样做!:)
select c.ProfileId, Count(*) from @tblCheck as a
inner join Profile_attribute as b on a.AttributeID = b.AttributeID and a.Value = b.Value
inner join Profile as c on c.ProfileID = b.ProfileID
Group by c.ProfileID