0

I've created a query that gives prices for every product ordered by creation date.

What I now need is to only return one row per product, i.e. one price per product.

SELECT p.product_id, p.price, p.creation_date
FROM PRICE p
INNER JOIN PRODUCT pr
ON p.product_id = pr.product_id 
AND p.filter_id = 3 
AND (p.store_id IN (1,2,3,4) OR p.price_type = 'A')
ORDER BY p.creation_date DESC

Currently this query returns several prices per product, since several match, but I only want the newest one of those. The ORDER BY p.creation_date DESC gives the price I want as the first in the list, I want that first entry to be the only result for that product.

I've tried rownum = 1, but that only gives one result for the whole query. Please note that this is an Oracle Database, so as far as I know TOP does not work, same goes for LIMIT.

I've treid googling it, but I can't find examples showing exactly this issue.

I forgot to mention: There are some prices which have the same creation date for the same product, so there has to be a limit of only giving the first entry for those too

4

3 回答 3

2

使用 row_numer() 窗口函数仅获取最新行:

select * from (
  SELECT 
    p.product_id, 
    p.price, 
    row_number() over (partition by product_id order by p.creation_date desc) rn,
    p.creation_date
  FROM PRICE p
  INNER JOIN PRODUCT pr
    ON p.product_id = pr.product_id 
    AND p.filter_id = 3 
    AND (p.store_id IN (1,2,3,4) OR p.price_type = 'A') 
) where rn = 1
于 2012-12-17T10:32:45.947 回答
2

你可以试试这个来获取产品的价目表

SELECT p.product_id, p.price ,first_value(p.price) over (partition by product_id
                                            order by  p.creation_date desc) new_price, p.creation_date
    FROM PRICE p
    INNER JOIN PRODUCT pr
    ON p.product_id = pr.product_id 
    AND p.filter_id = 3 
    AND (p.store_id IN (1,2,3,4) OR p.price_type = 'A') 
于 2012-12-17T09:28:41.553 回答
1

我不明白为什么您需要加入产品,因为...您在返回的行中没有使用任何产品行...

您可以尝试:

SELECT p.product_id, MAX(p.price),  p.creation_date
FROM PRICE p
INNER JOIN 
   (SELECT pm.product_id, MAX(pm.creation_date)
    FROM PRICE pm
    GROUP BY pm.product_id) most_recent_price
    ON most_recent_price.product_id = p.product_id
WHERE p.filter_id = 3 
AND (p.store_id IN (1,2,3,4) OR p.price_type = 'A')
GROUP BY p.product_id, p.creation_date
于 2012-12-17T09:30:22.787 回答