我遇到了查询的性能问题,并想知道如何简化它。
我有一张表“评估”(样本,类别,陪审团,价值) 并创建了一些自定义函数来获得每个样本的平均值,所以我有这个观点:
CREATE VIEW Results AS
SELECT Sample,
Category,
IFNULL(COUNT_VALID(Value),0) || ' / ' || COUNT(Value) AS Valid,
CUSTOM_MEAN(Value) AS Mean,
CUSTOM_MEDIAN(Value) AS Median
FROM Evaluations GROUP BY Sample, Category;
然后我想要另一个字段告诉我每个样本是否在其类别的30%最佳值样本中。使用TOP(X)PERCENT是完美的,但似乎H2不支持它所以我做了第二个视图,计算类别中的位置乘以100,除以类别中的总数并与30相比:
CREATE VIEW Res AS
SELECT R1.*,
CASE
WHEN (
((SELECT COUNT(*) FROM Results R2
WHERE R2.Category = R1.Category
AND (R2.Mean > R1.Mean OR (R2.Mean = R1.Mean AND R2.Median > R1.Median))) + 1) * 100
/
(SELECT COUNT(*) FROM Results R2 WHERE R2.Category = R1.Category) )
> 30
THEN 'over 30%'
ELSE 'within 30%'
END as 30PERCENT
FROM Results R1 ORDER BY Mean DESC, Median DESC;
这可以正常工作但只有500条记录需要一些时间来检索结果。 有人能告诉我一种更有效的方法来构建这个查询吗?
谢谢和问候!