开发者

T-SQL Query Self join via Date Table

开发者 https://www.devze.com 2023-03-04 06:13 出处:网络
I am trying to write a query that joins a table to itself via a date table.The date table is populated with a day per row with dates for over 200 years (don\'t ask I didn\'t design it). It has a colum

I am trying to write a query that joins a table to itself via a date table. The date table is populated with a day per row with dates for over 200 years (don't ask I didn't design it). It has a column for the date and one for previous working date (i.e. if its a Monday the prev date will be the previous Friday).

The other table lets call it Prices has a date column and an id to determine the type of price that comes once each day. I need to join Prices against itself via the date table to have each day alongside the previ开发者_StackOverflow中文版ous day using the type column to determine which ones belong with each other.

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

Any Ideas?


Maybe like this:

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


Something like:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号