Jika persyaratan tetap untuk pivot 3 harga dalam satu rangkaian, maka gunakan ROW_NUMBER()
akan memungkinkan pemberian angka-angka ini 1, 2, 3 dan dari sana ada penggunaan sederhana case expressions
dengan group by
:
untuk 3 harga terendah:
SELECT
a.article_id
, MAX(CASE
WHEN a.price_seq = 1 THEN p.price END) AS price_1
, MAX(CASE
WHEN a.price_seq = 2 THEN p.price END) AS price_2
, MAX(CASE
WHEN a.price_seq = 3 THEN p.price END) AS price_3
FROM (
SELECT
article_id
, price_valid_from
, price_id
, ROW_NUMBER() OVER (PARTITION BY article_id
ORDER BY p.price ASC) AS price_seq
FROM article
LEFT OUTER JOIN price p
ON (a.price_id = p.price_id)
) a
GROUP BY
a.article_id
ORDER BY
a.article_id
untuk 3 harga terbaru
SELECT
a.article_id
, MAX(CASE
WHEN a.price_seq = 1 THEN p.price END) AS price_1
, MAX(CASE
WHEN a.price_seq = 2 THEN p.price END) AS price_2
, MAX(CASE
WHEN a.price_seq = 3 THEN p.price END) AS price_3
FROM (
SELECT
article_id
, price_valid_from
, price_id
, ROW_NUMBER() OVER (PARTITION BY article_id
ORDER BY price_valid_from DESC) AS price_seq
FROM article
) a
LEFT OUTER JOIN price p
ON (a.price_id = p.price_id)
GROUP BY
(a.article_id)
ORDER BY
a.article_id