2011-05-11 44 views
0

我想写一个查询,通过日期表连接到自己的表。日期表每天填充一天,日期超过200年(不要问我没有设计它)。它有一个日期栏和一个前一个工作日期栏(如果它的一个星期一的前一天是上一个星期五)。T-SQL查询自加入通过日期表

另一张表让我们称之为价格有一个日期列和一个ID来确定每天到来的价格类型。我需要通过日期表来加入价格,以便每天与前一天一起使用类型列来确定哪些属于对方。

Todays Date | Todays Price | Previous Working Day Date | Previous Working Day Price | Price Type 

任何想法?

回答

1

也许是这样的:

SELECT 
    today.Date, 
    today.Price, 
    yesterday.Date, 
    yesterday.Price, 
    today.PriceType 
FROM Price today 
    INNER JOIN dates d ON today.Date = d.Date 
    INNER JOIN Price yesterday 
    ON d.YesterdayDate = yesterday.Date AND today.PriceType = yesterday.PriceType 
1

喜欢的东西:

SELECT today.Date, today.Price, lwd.Date, lwd.Price, today.TypeId 
FROM Price AS today 
JOIN Date AS d 
ON d.Date = today.Date 
JOIN Price AS lwd 
ON lwd.Date = d.PreviousWorkingDate