每行最接近的值

时间:2014-01-26 01:02:05

标签: sql postgresql postgresql-9.2

我有一张产品价格表,每个价格都有一个类别。对于代表产品的每一行,我需要知道产品价格的最低价格范围,按产品类别划分

exced查询应该产生额外的“预期L值”和“预期R值”列。

逻辑是:     L值<价格&lt; R值 哪里 L值和R值是最接近的价格

在下表中,我们只有一个R值,因为没有值&lt;价格 而对于R值,它是12,因为它大于价格,它也是最接近的。

第二行(ID 2)我们同时拥有L和R价格,因为: 10(L价格)&lt; 12(价格)&lt; 32(R价格) L和R必须按类别分组计算

|  ID   | idcategory |  price  | expected L value  | expected R value  |
|   1   |     1      |   10    |         NULL      |         12        |
|   2   |     1      |   12    |         10        |         32        |
|   3   |     1      |   43    |         32        |         NULL      |
|   4   |     1      |   32    |         22        |         43        |
|   5   |     2      |   38    |         10        |         NULL      |
|   6   |     2      |    8    |         3         |         10        |
|   7   |     2      |    3    |         NULL      |          8        |
|   8   |     2      |   10    |          8        |         38        |

适用于postgres 9.2

最后我通过使用滞后和分区引导得到它,这里的细节:


--calculate the max
with prices_ord as (
  select idcategory , max(price)  max
  from prices
  group by idcategory 
),
--gets the l-r values with lag and lead from the partition sorted by price
interval_prices as (
  select  id, idcategory, price,
    lag(price, 1) over (partition by idcategory order by price) l_price,
    lead(price, 1) over (partition by idcategory order by price) r_price
  from prices
)
--returns the table joining by idcategory
select pi.* 
from prices_ord po
inner join interval_prices pi on po.idcategory= pi.idcategory

1 个答案:

答案 0 :(得分:0)

这可能不是最有效的查询,但我现在想不出更好的查询:

select p.id, 
       p.idcategory, 
       p.price, 
       (select max(lval.price) from prices lval where lval.price < p.price and lval.idcategory = p.idcategory) as l_value,
       (select min(rval.price) from prices rval where rval.price > p.price and rval.idcategory = p.idcategory) as r_value
from prices p
order by p.id;

这是一个SQLFiddle:http://sqlfiddle.com/#!15/e8c0b/1