我基本上是在尝试使用 NHibernate ICriteria 接口创建此查询:
SomeTable 1:n 另一个表
SomeTable有列:PrimaryKey、NonAggregateColumn
AnotherTable有列:PrimaryKey、ForeignKey、AnotherNonAggregate、YetAnotherNonAggregate
SELECT
table1.NonAggregateColumn,
subquery.SubQueryAggregate1,
subquery.SubQueryAggregate2
FROM
SomeTable AS table1
LEFT JOIN
(
SELECT
table2.ForeignKey,
COUNT(table2.AnotherNonAggregate) AS SubQueryAggregate1,
AVG(table2.YetAnotherNonAggregate) AS SubQueryAggregate2
FROM AnotherTable AS table2
GROUP BY (table2.ForeignKey)
) AS subquery ON subquery.ForeignKey = table1.PrimaryKey
很明显,使用投影子查询效率不高,因为 SQL 必须扫描表两次(每个聚合一个投影子查询)。
使用多个 GROUP BY 也不是很有效。
有解决方案吗?到目前为止,我一直在使用原始 SQL,但这对于复杂的报告来说变得很笨拙。