2013-11-04 50 views
1

我有了價格歷史等幾個項目表 -SQL:結合域,但沒有重複

Item Date Price 
    X 1Jan13 100 
    X 2Jan13 110 
... 
    X 31Dec13 115 
    Y 1Jan13  50 
    Y 2Jan13  47 
... 
    Y 31Dec13 58 

等。

我剛剛寫了一個查詢來找出特定商品的價格連續三天沒有變化的日期。使用兩個內部連接我的查詢返回輸出的格式如下 -

Item Date1  Date2  Date3 Price 
X 2Jun13 3Jun13 4Jun13 110 
X 3Jun13 4Jun13 5Jun13 110 
... 
X 29Dec13 30Dec13 31Dec13 125 
Y 29Mar13 30Mar13 31Mar13 55 

現在,我的問題是我怎麼能得到輸出格式如下

Item Date  Price 
X 2Jun13 110 
X 3Jun13 110 
X 4Jun13 110 
X 5Jun13 110 
X 29Dec13 125 
X 30Dec13 125 
X 31Dec13 125 

等所有項目。也就是說,如何組合/合併三個日期字段(無重複)以生成單個日期字段?因爲正如你所看到的,與我現在所得到的相比,所需的格式更容易閱讀。

下面是我用我的查詢代碼:

Select x.* 
From (
     Select T1.ItemName As Item, T1.Date As Date_3, T2.Date As Date_2, T3.Date As Date_1, 
     Round((T1.Price - T2.Price), 2) As Change, Round((T1.Price - T3.Price), 2) As Change_2, T1.Price As Price 
     From MarketData As T1 Inner Join MarketData As T2 On T1.ItemName = T2.ItemName 
     Inner Join MarketData As T3 On T2.ItemName = T3.ItemName 
     Where (T1.Date = T3.Date + 2 Or (DatePart(DW, T3.Date) In (5, 6) And T1.Date = T3.Date + 4)) And 
    (T2.Date = T3.Date + 1 Or (DatePart(DW, T3.Date) = 6 And T2.Date = T3.Date + 3)) 
) As x 
Where x.Change = 0 And x.Change_2 = 0 

任何幫助深表感謝。

+0

請上傳您所使用的代碼。 – Joe

+2

請告訴我們您到目前爲止所嘗試的內容,並告訴我們您正在使用哪種RDBMS? –

回答

1

如果你的數據庫支持工會,你可以這樣做:

select Item, Date, Price from 
(
select Item, Date1 as Date, Price from (<1st select here>) res 
union 
select Item, Date2 as Date, Price from (<1st select here>) res 
union 
select Item, Date3 as Date, Price from (<1st select here>) res 
) table 
order by Date 

你也可以變身< 1日在這裏選擇>在子查詢中,並進一步otimize的SQL。

編輯:這裏是帶有您的查詢,我明明沒有嘗試,但希望這將有助於:)

select table.Item, table.Date, table.Price from 
(
select Item, Date1 as Date, Price from tdp res 
union 
select Item, Date2 as Date, Price from tdp res 
union 
select Item, Date3 as Date, Price from tdp res 
) table, 
(Select x.* 
From (
     Select T1.ItemName As Item, T1.Date As Date_3, T2.Date As Date_2, T3.Date As Date_1, 
     Round((T1.Price - T2.Price), 2) As Change, Round((T1.Price - T3.Price), 2) As Change_2, T1.Price As Price 
     From MarketData As T1 Inner Join MarketData As T2 On T1.ItemName = T2.ItemName 
     Inner Join MarketData As T3 On T2.ItemName = T3.ItemName 
     Where (T1.Date = T3.Date + 2 Or (DatePart(DW, T3.Date) In (5, 6) And T1.Date = T3.Date + 4)) And 
    (T2.Date = T3.Date + 1 Or (DatePart(DW, T3.Date) = 6 And T2.Date = T3.Date + 3)) 
) As x 
Where x.Change = 0 And x.Change_2 = 0) as tdp 
order by Date 
+0

有沒有一種方法可以用'x'代替<1st select here>,而不是複製整個查詢三次?如果x具有我查詢的結果,請查看上述查詢的代碼,如果不清楚的話。謝謝。 – user2696565

+1

是的,如果你在SQL Server中使用CTE。 – makciook

+1

爲避免複製三次查詢,可以使用「公用表表達式」(WITH query AS ...)或臨時表。 – Twinkles