2010-10-29 14 views
0

我需要将以下Linq中的相关子查询转换为Sql。我能够实现左外部连接部分。但是,在子查询中分组是我得到不正确的结果。Linq外连接子查询中的分组

SELECT 
    ae.Id,ae.Title 
,(select COUNT(*) from [dbo].[AssociationEventRSVP] where RSVPStatus='Y' 
group by AssociationEventId, RSVPStatus having RSVPStatus='Y' 
and AssociationEventId=ar.AssociationEventId) as CountYes 
,(select COUNT(*) from [dbo].[AssociationEventRSVP] 
group by AssociationEventId, RSVPStatus having RSVPStatus='N' 
and AssociationEventId=ar.AssociationEventId) as CountNo 
    FROM [dbo].[AssociationEvents] as ae 
    left outer join AssociationEventRSVP as ar 
    on ae.Id=ar.AssociationEventId 

在此先感谢您的帮助。

图沙·M.

回答

1

我第一次重构查询到这一点:

SELECT 
ae.Id, 
ae.Title, 
(select COUNT(*) FROM [dbo].[AssociationEventRSVP] WHERE RSVPStatus='Y' AND AssociationEventId=ae.Id) AS CountYes, 
(select COUNT(*) FROM [dbo].[AssociationEventRSVP] WHERE RSVPStatus='N' AND AssociationEventId=ae.Id) AS CountNo 
FROM [dbo].[AssociationEvents] as ae 

这里是一个简单的(不一定有效)的LINQ to SQL转换:

var results = from ae in context.AssociationEvents 
       select new 
       { 
        ae.Id, 
        ae.Title, 
        CountYes = context.AssociationEventRSVP.Where(aer => aer.RSVPStatus == "Y" && aer.AssociationEventId == ae.Id).Count(), 
        CountNo = context.AssociationEventRSVP.Where(aer => aer.RSVPStatus == "N" && aer.AssociationEventId == ae.Id).Count() 
       };