我需要将Linq中的以下相关子查询转换为Sql。我能够实现左外连接部分。但是,在子查询中进行分组是我得到错误结果的地方。
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
提前感谢您的帮助。
Tushar M。
答案 0 :(得分: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()
};