I need help, in building SQL (Query or CTE) for below scenario
Problem : I need to join my Master Table A with detail Table B to find out matching record/row(for each record of TableA) from Table B having same itemType, country having max(TransactionTime) && TransactionTime < EntryTime from table A for corresponding record.
OrderTable
id itemType country EntryTime
1. Item1 IND 12:01:20:291
2. Item2 USA 14:11:22:299
3. Item4 LON 18:01:17:112
4. Item1 SIN 20:05:30:020
5. Item3 HKG 22:02:23:442
StockPrice Table
id itemType country TransactionTime Price
1. Item1 IND 12:01:20:291 10.12
2. Item2 USA 14:11:22:299 50.12
3. Item4 LON 18:01:17:112 02.12
4. Item1 SIN 20:05:30:020 10.67
5. Item3 HKG 22:02:23:442 11.22
6. Item1 IND 12:01:20:291 10.14
7. Item2 USA 14:11:22:299 50.11
8. Item4 LON 18:01:17:112 02.10
9. Item1 SIN 20:05:30:020 10.90
10. Item3 HKG 22:02:23:442 11.37
11. Item1 IND 12:01:20:291 10.10
12. Item2 USA 14:11:22:299 50.01
13. Item4 LON 18:01:17:112 02.11
14. Item1 SIN 20:05:30:020 10.89
15. Item3 HKG 22:02:23:442 11.90
Please help to advise, let me know in comment if anymore details are required
Tried Solution
Select o.id, o.itemType, o.country, o.EntryTime, o.sp.price
from OrderTable o join
StockPrice sp
ON o.country = sp.country and o.itemType = sp.itemType and
o.EntryTime = (select top 1 TransactionTime from StockPrice spIN where o.country = spIN.country and o.itemType = spIN.itemType and
and spIN.spIN.TransactionTime < o.EntryTime order by spIN.TransactionTime)
Somehow result set have more then expected rows
Issues with above query..
- From above query i am getting result for only first row from Table A.
- In case Table B has more then one row having exact time as max TransactionTime, returned result will be corresponding to number of rows in table b.