有五个专栏。如何获取行(而不是列)的平均值,以及平均数应减去最大值和最小值。
如果有重复的最大值或(和)最小值,如何将它们全部排除?
我的数据结果应该是这样。
Average_MIN_MAX_excluded
-------------------------
3.33333333
5.33333333
我的数据集如下;
WITH DATAA AS
(SELECT 3 c1,5 c2,4 c3,3 c4 ,1 c5 FROM DUAL
UNION
SELECT 1 c1,3 c2,6 c3,9 c4 ,7 c5 FROM DUAL)
SELECT c1, c2, c3, c4, c5 FROM DATAA;
select ((c1 + c2 + c3 + c4 + c5) -
greatest( c1, c2, c3, c4, c5 ) -
least( c1, c2, c3, c4, c5 ))/ 3
from DATAA
将是一种方法。这是liveSQL link
这是使用LATERAL JOIN
或LATERAL JOIN
的好地方:
CROSS APPLY
如果需要,此方法可轻松排除1,2,3最高/最低值。
SELECT *
FROM t
CROSS APPLY (
SELECT AVG(c) AS Average_MIN_MAX_excluded
FROM (
SELECT c, ROW_NUMBER() OVER(ORDER BY c) rn
FROM (
SELECT c1 c FROM dual UNION ALL
SELECT c2 FROM dual UNION ALL
SELECT c3 FROM dual UNION ALL
SELECT c4 FROM dual UNION ALL
SELECT c5 FROM dual)
)
WHERE rn NOT IN (1,5)
) s;
我认为您可以将db<>fiddle demo和unpivot
与analytical function
和group by
聚合函数一起使用,如下所示:
average
请参见WITH DATAA AS
(
SELECT 3 c1,5 c2,4 c3,3 c4 ,1 c5 FROM DUAL
UNION
-- case with same value at min for two columns
SELECT 1 c1,5 c2,4 c3,3 c4 ,1 c5 FROM DUAL
UNION
SELECT 1 c1,3 c2,6 c3,9 c4 ,7 c5 FROM DUAL)
-- your query starts from here
select rn, avg(val) from
(select rn, val,
max(val) over (partition by rn) maxval,
min(val) over (partition by rn) minval
from
(SELECT rownum rn, c1, c2, c3, c4, c5
FROM DATAA)
unpivot
(val for vals in (c1,c2,c3,c4,c5)))
where val not in (maxval, minval)
group by rn
演示。
干杯!