postgres“ntile(2)over(按列排序)”无效订单

时间:2018-03-07 11:57:43

标签: postgresql

我注意到在大桌子上使用postgres ntile的奇怪行为。它并没有真正正确地排序。例子是:

select tile, min(price) as minprice, max(price) as maxprice, count(*) 
from (
    select ntile(2) over(order by price ASC) as tile, adult_price as price
    from statistics."trips"
    where back_date IS NULL AND adult_price IS NOT null
    and departure = 297 and arrival = 151
) as t
group by tile

我的观点给出了非常奇怪的结果:

tile    minprice    maxprice    count
1       2250        5359        74257
2       2250        27735       74257
关于count和maxprice没什么特别的。对于某些数据集可能是正确的。但是min_price表明排序有问题。

第二个瓷砖的min_price如何从第一个小于max_price?但这是通过检查内部选择的结果来批准的。它仅部分订购,并且有一些“混合”部件,价格订单被打破。

手动拆分2部分显示相同的最低和最高价格,但中间价格不同:

select * from (
    select row_number() over (order by adult_price ASC) as row_number, adult_price
    from statistics."trips"
    where back_date IS NULL AND adult_price IS NOT null
    and departure = 297 and arrival = 151
    order by price
) as t
where row_number IN(1, 74257, 74258, 148514)

row_number adult_price
1          2250
74257      4075
74258      4075
149413     27735

1 个答案:

答案 0 :(得分:0)

一定是令人困惑的列名。

外部查询中的列price实际上是内部查询中的adult_price,而ntile是按内部查询中的不同列(price计算的排序)。

相关问题