I need to create a start end range. I need to left join table2 onto table1 where min(anotherDate) > someDate for the same custId. Notice 2012-11-16 14:33:37 was excluded because it was not the min for someDate: 2011-07-07 13:27:57
SELECT T1.CustID
, T1.SomeDate
, T2.MinDate
FROM Table1 T1
INNER JOIN (SELECT CustID
, MIN(AnotherDate) as MinDate
FROM Table2
GROUP BY CustID) T2 ON T1.CustID = T2.CustID
Essentially this with the obvious min() being placed somewhere where it is allowed:
left join table2 t2 on t1.custId = t2.custId and t2.anotherDate > min(t1.someDate)
this join without the min() gives me ALMOST what I want, except there are dupes. It isn’t returning one instance of t2’s date. And throwing a simple min() on t2’s date will make it return only one date per custId instead of a valid date range for all rows.
SELECT T1.CustID
, T1.SomeDate
, MIN(T2.AnotherDate)
FROM Table1 T1
LEFT JOIN Table2 T2 ON T1.CustID = T2.CustID
AND T2.AnotherDate >= T1.SomeDate
GROUP BY T1.CustID
, T1.SomeDate
Unfortunately that produces the same undesirable results. Remove the min and group by and it’s almost there, but it shows all possibilities rather than just the next occurrence. Throwing a min on the whole select will produce the same date for all columns
That doesn’t make sense. I created test tables with your data. Based on your data, the results for the last query I gave you (though I changed it to inner join - though left join results match in this case) are:
which would be correct - it shows the minimum another date from table two on each some date. If you change the some date on the 2nd row of table 1 to 8/1/12, the results change to: