我必须在mysql表上实现多个排名和中位数计算。 该表看起来像:
ps_eur_agreg_lots(id_lot,id_customer,variete,qualite_presentation,defauts_graves)
(实际上,它是来自许多表的聚合视图。)
id_customer和variete用于过滤具有更改where子句的子集(例如:WHERE id_customer = 5和variete = agata,从表单生成),我将在其上对qualite_presentation和defauts_graves值进行排名(可以将其视为标记),并计算我的子集上这些标记的中值。
以下是我用于带有where子句的值的排名请求:
SELECT id_lot,@curQRank := @curQRank+1 as qrank
FROM ps_eur_agreg_lots, (SELECT @curQRank :=0) r
WHERE variete='agata'
ORDER BY qualite_presentation DESC, prc_total_def ASC)
as tqrank
这将返回排名关系(id_lot,qrank),我将与ps_eur_aggr_lots一起加入 获得排名关系(这可以用于多个标准)。
以下是我计算中值的请求:
SELECT AVG(al.qualite_presentation) as median
FROM ps_eur_agreg_lots al
JOIN
(SELECT id_lot,@curQRank := @curQRank+1 as qrank
FROM ps_eur_agreg_lots, (SELECT @curQRank :=0) r
WHERE variete='agata'
ORDER BY qualite_presentation DESC, prc_total_def ASC)
as tqrank
ON al.id_lot=tqrank.id_lot
WHERE tqrank.qrank in (
(SELECT
round((count(*)+1)/2,0) as qm1ind
FROM
(SELECT id_lot,@curQRank := @curQRank+1 as qrank
FROM ps_eur_agreg_lots, (SELECT @curQRank :=0) r
WHERE variete='agata'
ORDER BY qualite_presentation DESC, prc_total_def ASC
) as tqrank) ,
(SELECT
round((count(*)+2)/2,0) as qm2ind
FROM
(SELECT id_lot,@curQRank := @curQRank+1 as qrank
FROM ps_eur_agreg_lots, (SELECT @curQRank :=0) r
WHERE variete='agata'
ORDER BY qualite_presentation DESC, prc_total_def ASC
) as tqrank)
)
这个请求完成了这个工作,但是使用树时间相同的排名请求,看起来很难看。
这个中值计算的想法是取两个(或一个)中心值(eaven或奇数情况)的平均值。 我尝试使用临时排名表,但我得到“无法重新打开表”错误。
我想我可以将请求拆分成一些中间的请求,但看不到真正令人满意的方式。欢迎提示。
答案 0 :(得分:0)
取消第二和第三等级,而不是使用一对联合简单子查询的连接
SELECT AVG(al.qualite_presentation) as median
FROM ps_eur_agreg_lots al
JOIN
(
SELECT id_lot,@curQRank := @curQRank+1 as qrank
FROM ps_eur_agreg_lots, (SELECT @curQRank :=0) r
WHERE variete='agata'
ORDER BY qualite_presentation DESC, prc_total_def ASC
) as tqrank
ON al.id_lot=tqrank.id_lot
INNER JOIN
(
SELECT round((count(*)+1)/2,0) as qm1ind
FROM ps_eur_agreg_lots
WHERE variete='agata'
UNION
SELECT round((count(*)+2)/2,0) as qm1ind
FROM ps_eur_agreg_lots
WHERE variete='agata'
) tqrank2
ON tqrank.qrank = tqrank2.qm1ind
GROUP BY qualite_presentation