2013-04-11 51 views
0

我的表是這樣的:添加列 「以前日期」

PartNr,ProductionSite,ProductionType,PODate,PoPrice,PoCurrency

前三列定義獨特的產品。我想要做的是添加一個包含以前採購訂單日期的列,以便制定價格有效的日期範圍。下面是例子:

PartNr.... Site.... Type.... Date 

111111  BBBBB  100  2008-06-10 

111111  BBBBB  100  2012-01-18 

111111  BBBBB  100  2012-01-30 

111111  AAAAA  100  2008-06-10 

111111  AAAAA  100  2012-01-18 

111111  AAAAA  100  2012-01-30 

我想這

PartNr.... Site .... Type .... Date .... Added Column 

111111 BBBBB  100  2008-06-10 ...  0 

111111 BBBBB  100  2012-01-18 ...  2008-06-10 

111111 BBBBB  100  2012-01-30 ...  2012-01-18 

111111 AAAAA  100  2008-06-10 ...  0 

111111 AAAAA  100  2012-01-18 ...  2008-06-10 

111111 AAAAA  100  2012-01-30 ...  2012-01-18 
+0

你想'ALTER'表添加它,或者只是在查詢中返回列? – Patashu 2013-04-11 08:37:51

回答

0

你想,其選擇低於當前行的日期的最大日期(和匹配partnr等),就像一個子查詢:

select PartNr, ProductionSite, ProductionType, PODate, PoPrice, PoCurrency, 
(select max(PODate) from table t2 where t2.PODate < t1.PODate and t2.PartNr = t1.PartNr and t2.ProductionSite = t1.ProductionSite and t2.ProductionType = t1.productionType 
as added_column from table t1 

您也不需要將它作爲表中的列。請記住,數據庫設計的基本原則是 - 從不儲存你可以計算的東西*。

*除非你的數據庫永遠不會或幾乎不會改變,你需要它真的很快。這被稱爲「數據倉庫」。