如何将这两个SQL查询合并为一个?

时间:2012-01-11 14:26:25

标签: sql sql-server

SQL Server 2005.表模式是MarketdataID,数据类型,日期,来源,坐标,值。 PK是除Value之外的一切。数据可能来自多个来源,可能在指定日期不可用;我希望在给定日期之前获得最近的日期,并且每个日期只有一个来源。

SELECT top 1 [Source], [Date] FROM Market
WHERE MarketDataID = ?
AND DataType = ?
AND [Date] <= ?
order by [date] desc, [source]

然后在此查询中使用返回的日期和来源:

SELECT [Coordinate], [Value] FROM Market
WHERE MarketDataID = ?
AND DataType = ?
AND [Date] = ?
AND [Source] = ?
ORDER BY [coordinate]

1 个答案:

答案 0 :(得分:5)

SELECT [Coordinate], [Value]
  FROM Market AS m0
  JOIN (SELECT TOP 1 m2.[Source], m2.[Date], m2.MarketDataID, m2.DataType
          FROM Market AS m2
         WHERE m2.MarketDataID = ?
           AND m2.DataType = ?
           AND m2.[Date] <= ?
           ORDER BY m2.[Date] DESC, m2.[Source]
       ) AS m1
    ON m0.[Source]     = m1.[Source]
   AND m0.[Date]       = m1.[Date]
   AND m0.MarketDataID = m1.MarketDataID
   AND m0.DataType     = m1.DataType
 ORDER BY [coordinate]