Hvis kravet forbliver for en pivot på 3 priser i en serie, skal du bruge ROW_NUMBER()
vil gøre det muligt at give disse tal 1, 2, 3, og derfra er en simpel brug af case expressions
med en group by
:
til 3 laveste priser:
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
til 3 seneste priser
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