2017-03-03 29 views
0

需要我有一個Products表下面的列SQL服務器 - 產品和他們的最新信息,從歷史表

ProductId - INT - PK 
Name - Varchar 
Price Decimal 

我有另一個表ProductPriceHistory

當商品價格更新,使用觸發器,我在該表中存儲新舊價格。此表格具有以下列

ProductPriceHistoryId 
Name 
OldPrice 
NewPrice 
UpdateDate 

我可以根據Name列加入此表。

現在的問題是,在我的結果集 - 我想要得到Product.NameProduct.Price和(用於獲取表ProductPriceHistory最後更新的值)ProductPriceHistory.NewPrice

挑戰是在歷史表中,我根據不同的日期爲每個產品準備了很多行。對於每種產品,我需要從最新一行中獲取該產品的信息。

回答

0

您應該將ProductId存儲在歷史記錄表中,因爲它是唯一的,然後按照該值加入表。

然後,按日期降序排列查詢,限制1(或選擇排名前1位的字段來自...)。這隻會給你最新的更新。

編輯:您的表格結構沒有標準化。它會更有意義,我要你的表是:

Products: 
ProductId 
Name 
Description 

Prices: 
ProductId 
Price 
UpdateDate 

然後將查詢將是:

SELECT TOP 1 Products.ProductId, Products.Name, Prices.Price, Prices.UpdateDate FROM etc 
+0

限制查詢返回行數nbmer不是標準sql,其可用性取決於dbms。 –

+0

修改爲包含「選擇頂部...」 – Stuart

0

這樣做與自身聚集加入歷史悠久的表的標準SQL的方式,在哪個產品中你選擇了最大日期。

select t1.Name, t1.Price, t2.NewPrice 
from Products t1 
join ProductPriceHistory t2 
on  t1.Name = t2.name 
join (
      select Name, max(UpdateDate) as MaxDate 
      from ProductPriceHistory 
      group by Name 
     ) t3 
on  t2.Name = t3.Name and t2.UpdateDate = t3.MaxDate 
相關問題