Combining 2 SQL SELECT queries Into one
I have (2) tables (1) is Prices
and the other is Orders
Prices:
Symbol varchar
Open decimal
High decimal
Low decimal
Date DateTime
Orders:
Ticker varchar
Enter decimal
EntDate datetime
Exit decimal
ExtDate datetime
I'd like a query that give me all the pricing data for a specific datetime range and all the orders for that symbol for that same datetime range:
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')
Obviously this just does not work, I get multiple listings for Orders repeated for every line of Price Data.
Example Prices Table
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:1开发者_开发问答0 AM
Example Orders Table
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
Example Output for Prices and Orders Query with Date and EntDate < 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
you need to have P1.Symbol and not T1.Symbol
Consider joining only the orders for the same day as the Price
row:
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)
精彩评论