Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

sql - How to find changed prices in last two purchase invoices

Postgres 9.1+ holds purchase invoices in two tables:

Invoice headers:

create table dok (
  dokumnr serial primary key,
  invdate date not null
  );

Invoice rows:

create table rid (
  id serial primary key,
  dokumnr int not null references dok,
  product char(20),
  quantity numeric(12,5) not null,
  price   numeric(12,2)
  );

How to find changed prices in last two purchase invoices ?

Result table should contain 3 columns:

  • product
  • prices and quantities in last (by date) invoice
  • prices and quantities in invoice immediately before (by date and dokumnr) last invoice

Result should contian only products where any prices for same product in last two invoices are different. How to create query which returns this from invoice headers and rows?

Postgres 9.1 and later versions are used.

Single invoice can contain same product multiple times with different prices.

Update

Tried using script below. It does not return any rows.

It should return prices with quantities, like

5 pcs with 2;6 pcs with 1 in last price column and 4 pcs with 2 in previous price column. If at least one price is different, columns should contain all prices and quantities separated by ;

It there are different prices in same day invoices, they should also returned. Probably ordering should include dokumnr field in additon to invdate.

create temp table dok (
  dokumnr serial primary key,
  invdate date not null
  ) on commit drop ;

create temp table rid (
  id serial primary key,
  dokumnr int not null references dok,
  product char(20),
  quantity numeric(12,5) not null,
  price   numeric(12,2)
  ) on commit drop ;

 insert into dok  values (1,'2016-10-02'), (2,'2016-10-03');

insert into rid values
(1,1,'p',4, 2),
(2,2,'p',5, 2),
(3,2,'p',6, 1)
 ;

 with top2prices as (
select product
,max(case when rnk=1 then price end) latest_price
,max(case when rnk=2 then price end) latest_2_price
from ( 
select r.*,d.*
,dense_rank() over(partition by r.product order by d.invdate desc) rnk
from rid r 
join dok d on d.dokumnr = r.dokumnr
     ) t
group by product
)
select * from top2prices 
where latest_price <> latest_2_price
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...