50 | | with salesByPrice as (select au.art_id, |
51 | | p.price, |
52 | | p.price_eff_date, |
53 | | count(au.unit_id) as unitsSold, |
54 | | count(au.unit_id) * p.price as revenue |
55 | | from article_unit au |
56 | | join orders o on au.ord_id = o.ord_id |
57 | | join price p on au.art_id = p.art_id |
58 | | where o.ord_date >= p.price_eff_date |
59 | | and o.ord_date < coalesce( |
60 | | (select min(price_eff_date) |
61 | | from price p2 |
62 | | where p2.art_id = p.art_id |
63 | | and p2.price_eff_date > p.price_eff_date), |
64 | | '9999-12-31' |
65 | | ) |
66 | | group by au.art_id, p.price, p.price_eff_date) |
67 | | select a.art_name as articleName, |
68 | | sp.price as unitPrice, |
69 | | sp.price_eff_date as priceEffectiveDate, |
70 | | sp.unitsSold, |
71 | | sp.revenue |
72 | | from salesByPrice sp |
73 | | join article a on sp.art_id = a.art_id |
74 | | order by a.art_name,sp.price_eff_date; |
| 50 | with PriceChanges as ( |
| 51 | select |
| 52 | p.art_id, |
| 53 | p.price, |
| 54 | p.price_eff_date, |
| 55 | lag(p.price) over (partition by p.art_id order by p.price_eff_date) as prevPrice |
| 56 | from price p |
| 57 | ), |
| 58 | FilteredPrice as ( |
| 59 | select |
| 60 | art_id, |
| 61 | price, |
| 62 | price_eff_date |
| 63 | from PriceChanges |
| 64 | where prevPrice is null or abs(price - prevPrice) >= 1 |
| 65 | ), |
| 66 | SalesByPrice as ( |
| 67 | select |
| 68 | p.art_id, |
| 69 | fp.price, |
| 70 | fp.price_eff_date, |
| 71 | count(au.unit_id) as units_sold, |
| 72 | count(au.unit_id) * fp.price as revenue |
| 73 | from article_unit au |
| 74 | join orders o on au.ord_id = o.ord_id |
| 75 | join unit_price up on up.unit_id = au.unit_id |
| 76 | join price p on up.price_id = p.price_id |
| 77 | join FilteredPrice fp on p.art_id = fp.art_id |
| 78 | and p.price_eff_date = fp.price_eff_date |
| 79 | where o.ord_date >= fp.price_eff_date |
| 80 | and o.ord_date < coalesce( |
| 81 | (select min(fp2.price_eff_date) |
| 82 | from FilteredPrice fp2 |
| 83 | where fp2.art_id = fp.art_id |
| 84 | and fp2.price_eff_date > fp.price_eff_date), |
| 85 | '9999-12-31' |
| 86 | ) |
| 87 | group by p.art_id, fp.price, fp.price_eff_date |
| 88 | ) |
| 89 | select |
| 90 | a.art_name as articleName, |
| 91 | sp.price as unitPrice, |
| 92 | sp.price_eff_date as priceEffectiveDate, |
| 93 | sp.units_sold, |
| 94 | sp.revenue |
| 95 | from SalesByPrice sp |
| 96 | join article a on sp.art_id = a.art_id |
| 97 | order by a.art_name, sp.price_eff_date; |