如何对我的Postgres表中按值排序的所有值的50%求和?
在表格中我有值1
,2
,3
,4
,5
,6
,我想得到按值DESC排序的半值之和。结果将是4 + 5 + 6 = 15
另外,我可能只想获得1/3的值,所以我会得到6 + 5 = 11
Postgres中的SQL是否可行?像
这样的东西SELECT sum(value)
FROM (
SELECT value
FROM table
ORDER BY value DESC
LIMIT 50%
) subquery
答案 0 :(得分:1)
我会使用row_number()
和count()
:
SELECT sum(value)
FROM (SELECT value, ROW_NUMBER() OVER (ORDER BY value) as seqnum,
COUNT(*) OVER () as cnt
FROM table
) subquery
WHERE seqnum <= cnt * 0.5;
答案 1 :(得分:0)
with t (value) as (values (1),(2),(3),(4),(5),(6))
select sum(value)
from (
select value, percent_rank() over (order by value) as pr
from t
) S
where pr > 0.5
;
sum
-----
15
答案 2 :(得分:0)
我提出了我的版本:
SELECT sum(value)
FROM (
SELECT
value,
ntile(10)
OVER (
ORDER BY value DESC ) AS tile
FROM t
) subquery
WHERE tile >= 10*0.5;
这对count of values < ntile's N
不起作用,但最后我打算将其用于数千个值