将2个SQL SELECT查询合并为一个

时间:2011-08-28 16:15:09

标签: sql sql-server-2005

我有(2)表(1)是Prices而另一个是Orders

价格

Symbol varchar
Open decimal
High decimal
Low decimal
Date DateTime

订单

Ticker varchar
Enter decimal
EntDate datetime
Exit decimal
ExtDate datetime

我想要一个查询,它会为我提供特定日期时间范围的所有定价数据以及该符号在同一日期时间范围内的所有订单:

SELECT
   T1.Symbol
   , P1.Open
   , P1.High
   , P1.Low
   , P1.Close
   , P1.Date
   , O1.EntDate
   , O1.Enter
   , O1.ExtDate
   , O1.Exit
FROM Prices AS P1 
INNER JOIN ORDERS AS O1 ON O1.Ticker = P1.Symbol
WHERE P1.Date < CONVERT(datetime, '01/01/2012 10:00 AM')

显然这不起作用,我为每一行价格数据重复订单的多个列表。

示例价格表

 Sym    Open   High    Low    Close    Date
 ABC     1         3         1           2        1/1/2011 10:01 AM
 ABC     1         3         1           2        1/1/2011 10:02 AM
 ABC     1         3         1           2        1/1/2011 10:03 AM
 ABC     1         3         1           2        1/1/2011 10:04 AM
 ABC     1         3         1           2        1/1/2011 10:05 AM
 ABC     1         3         1           2        1/1/2011 10:06 AM
 ABC     1         3         1           2        1/1/2011 10:07 AM
 ABC     1         3         1           2        1/1/2011 10:08 AM
 ABC     1         3         1           2        1/1/2011 10:09 AM
 ABC     1         3         1           2        1/1/2011 10:10 AM

示例订单表

Sym  Enter   EntDate            Exit ExtDate
ABC   1      1/1/2011 10:-00    3    1/1/2011 10:02 AM  
ABC   1      1/1/2011 10:-03    3    1/1/2011 10:04 AM  

带有日期和EntDate的价格和订单查询的示例&lt; 1/1/2011 10:07 AM AND Symbol = ABC

Sym    Open   High    Low    Close               Date                Enter  EntDate                 Exit      ExtDate
ABC     1         3         1           2        1/1/2011 10:01 AM     1    1/1/2011 10:-00         3         1/1/2011 10:02 AM
ABC     1         3         1           2        1/1/2011 10:02 AM     1    1/1/2011 10:-03         3         1/1/2011 10:04 AM
ABC     1         3         1           2        1/1/2011 10:03 AM
ABC     1         3         1           2        1/1/2011 10:04 AM
ABC     1         3         1           2        1/1/2011 10:05 AM
ABC     1         3         1           2        1/1/2011 10:06 AM
ABC     1         3         1           2        1/1/2011 10:07 AM

2 个答案:

答案 0 :(得分:1)

你需要P1.Symbol 而不是T1.Symbol

答案 1 :(得分:0)

考虑仅加入与Price行相同的订单:

from    Prices as P1 
left join 
        Orders as O1 
on      O1.Ticker = P1.Symbol
        and p1.Date <= O1.ExtDate and O1.ExtDate < dateadd(day,1,p1.Date)