SQL:组合字段而不重复

时间:2013-11-04 13:04:11

标签: 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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分: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

您还可以转换&lt; 1st select here&gt;在子查询中并进一步确定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