在 postgresql 中比较来自相同 table 的值

Compare between values from the same table in postgresql

我有以下 table:

id partid orderdate       qty price
1    10     01/01/2017    10    3
2    10     02/01/2017    5     9
3    11     01/01/2017    0.5   0.001
4    145    02/01/2017    5     18
5    10     12/12/2016    8     7
6    10     05/07/2010    81    7.5

基本上,我想将最近一次采购的零件与 24 months 时间段内同一零件的其他采购进行比较。就此而言,比较 id=2id = 1,5

我想查看最新 orderdate(每件)的价格是否大于过去 24 个月该件的平均价格。

所以首先我需要计算平均价格:

partid avgprice
10       (3+9+7)/3=6.33  (7.5 is out of range)
11        0.001
145        18

我还需要知道每个零件的最新订购日期:

id partid
2    10
3    11
4    145

然后我需要检查 id=2、id=3、id=6(最新购买)是否大于平均值。如果他们是我需要 return 他们的 partid.

所以我应该有这样的东西:

id partid  avgprice   lastprice
2    10      6.33         9
3    11      0.001      0.001
4    145     18         18

最后我需要 return partid=10 因为 9>6.33

现在回答我的问题... 我不确定如何在 PostgreSQL 中找到最新订单。 我试过了:

select id, distinct partid,orderdate
from table
where orderdate> current_date - interval '24 months'
order by orderdate desc 

这给出:

ERROR: syntax error at or near "distinct".

我有点迷路了。我知道我想做什么,但我无法将其翻译成 SQL。任何人都可以帮忙吗?

这可以在没有 distinct 的情况下解决(无论如何这对数据库来说很重):

with avg_price as (
select partid, avg(price) as price
from table
where orderdate> current_date - interval '24 months'
group by partid
)
select f.id, f.partid, av.price, f.price
from (
        select id, partid, orderdate, price, rank() over (partition by partid order by orderdate desc)
        from table
    ) as f
join avg_price av on f.partid = av.partid
where f.rank = 1
and av.price < f.price 

获取每个零件的平均价格和每个价格的最后订单并加入这些:

select
  lastorder.id,
  lastorder.partid,
  lastorder.orderdate,
  lastorder.price as lastprice,
  avgorder.price as avgprice
from
(
  select
    partid, 
    avg(price) as price
  from mytable
  where orderdate >= current_date - interval '24 months'
  group by partid
) avgorder 
join
(
  select distinct on (partid)
    id,
    partid, 
    orderdate,
    price
  from mytable
  order by partid, orderdate desc
) lastorder on  lastorder.partid = avgorder.partid 
            and lastorder.price  > avgorder.price;