我在QueryOver中遇到问题,其中使用Group by并在where子句中有一些标准。想要在Having子句中使用SUM()值移动某些条件,但每次它出现在Where子句中并导致错误。 **Error** ="*An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference*"
Conjunction conjunction = Restrictions.Conjunction();
Conjunction havingconjun = Restrictions.Conjunction();
conjunction.Add<Vendor>(p => v.Name == "Some Vendor");
havingconjun.Add(Restrictions.Gt(
Projections.Sum(Projections.Property(() => v.Payments),
Convert.ToDouble(SomeInvoice.Value)));
var reportModels =
Session.QueryOver<Vendor>(() => v)
.Where(conjunction)
.Where(havingconjun)
.SelectList(list => list
.SelectGroup(() => v.Number).WithAlias(() => vModel.VendorNumber)
.SelectGroup(() => vtypeCode.Code).WithAlias(() => vModel.VendorType)
.SelectGroup(() => v.Name).WithAlias(() => vModel.VendorName))
.TransformUsing(Transformers.AliasToBean<VendorAnalysisReportModel>())
.List<VendorAnalysisReportModel>();
预期结果:
SELECT
V.VENDORNUMBER, V.VENDORTYPE, V.VENDORNAME, SUM(V.PAYMENTS)
FROM VENDOR V
WHERE V.NAME = "Some Vendor"
GROUP
BY V.VENDORNUMBER, V.VENDORTYPE, V.VENDORNAME
HAVING SUM(V.PAYMENTS) > somevalue
立即行动:
SELECT
V.VENDORNUMBER, V.VENDORTYPE, V.VENDORNAME, SUM(V.PAYMENTS)
FROM VENDOR V
WHERE V.NAME = "Some Vendor" AND
SUM(V.PAYMENTS) > somevalue
GROUP
BY V.VENDORNUMBER, V.VENDORTYPE, V.VENDORNAME
答案 0 :(得分:1)
很多人在NHibernate中找不到这个解决方案,然后我用一些简单的技巧来实现我的结果,直到NHibernate修复它才能解决这个问题。
在获得删除条件并执行简单查询后,它看起来像这样。
var reportModels =
Session.QueryOver<Vendor>(() => v)
.Where(conjunction)
.SelectList(list => list
.SelectGroup(() => v.Number).WithAlias(() => vModel.VendorNumber)
.SelectGroup(() => vtypeCode.Code).WithAlias(() => vModel.VendorType)
.SelectGroup(() => v.Name).WithAlias(() => vModel.VendorName))
.TransformUsing(Transformers.AliasToBean<VendorAnalysisReportModel>())
.List<VendorAnalysisReportModel>();
var vlst2 =
(from vendrs in reportModels orderby vendrs.VendorName ascending select vendrs)
.ToList<VendorAnalysisReportModel>().AsQueryable();
然后你可以在任何字段上放置任意数量的where子句。
vlst2 = vlst2.Where(p => p.OutstandingComm > Convert.ToDecimal(toDateComAmount.Value));
vlst2 = vlst2.Where(p => p.ToDateOrders < Convert.ToDecimal(toDateOrdAmount.Value));
我的问题已经解决,复杂的报告已成功运行,我们也在其他查询中也遵循相同的说法。
QF