I would like to generate the following sql from ICriteria
select c.Id,
sum(c.Amount) Amount,
(select COALESCE(max(AuditDate), c.WhenAdded) FROM Audit a WHERE c.Id = a.CId) StatusDate
from c
join l
on c.Id = l.CId
Group By c.Id, c.WhenAdded
So far i have
ICriteria crit = CurrentSession.CreateCriteria<C>()
.CreateAlias("L", "l")
.SetProjection(Projections.ProjectionList()
.Add(Projections.Group<C>(x => x.Id), "Id")
.Add(Projections.Sum("l.Amount"), "Amount")
.Add(Projections.SubQuery(DetachedCriteria.For<Audit>("ca")
.SetProjection(Projections.ProjectionList().Add(
Projections.SqlFunction("COALESCE",
NHibernateUtil.DateTime,
Projections.Max<ClaimAudit>(x=> x.AuditDate),
Projections.Property<C>(x => x.WhenAdded)), "StatusDate"))))
.SetResultTransformer(Transformers.AliasToBean<CDto>());
BUT I cannot get the parent column in the coalesce of the child subquery. I get the following exception
Could not find property C.WhenAdded
I know that the sub query is looking for a column called WhenAdded in the child query but not sure how to tell it to look in the parent?
Any ideas on how to acheive this?
ps. I need to do this in this converluted way otherwise i get an incorrect sum on amount. so no suggestions to re write without a subquery unless this is taken in to account.
Thanks.
move the coalesce out from the subquery and use an alias to restrict the Adit entries