I have two tables. I want to create a SQL query such that for each row in Table 1, I want find the first two rows in Table 2 such ms.Table2 > ms.Table1. The resulting output will be Table 1 with six additional columns added showing ms, bid, ask from Table 2 corresponding to first two rows from Table 2 where ms is just greater than ms in Table 1.
Given the large number of rows, doing a cross-join and then filtering may be too much (since this has to be done many times over multiple data, not just once). Looking for an efficient solution. I am new to SQL so feel this is bit much for me, though I did try a cross-join. Please help!
Table 1 (2000+ rows)
ms | price | bid | ask |
---|---|---|---|
34200106 | 1.48 | 1.46 | 1.5 |
34200106 | 1.48 | 1.46 | 1.5 |
34202812 | 1.56 | 1.53 | 1.56 |
34202815 | 1.56 | 1.53 | 1.56 |
34202823 | 1.56 | 1.53 | 1.56 |
34204227 | 1.56 | 1.53 | 1.57 |
34207137 | 1.56 | 1.55 | 1.57 |
34208496 | 1.57 | 1.56 | 1.57 |
34208938 | 1.57 | 1.55 | 1.57 |
34208938 | 1.57 | 1.55 | 1.57 |
34208943 | 1.57 | 1.55 | 1.57 |
34208951 | 1.57 | 1.56 | 1.57 |
Table 2 (300000+ rows)
ms | bid | ask |
---|---|---|
34200009 | 1.46 | 1.51 |
34200011 | 1.46 | 1.5 |
34200106 | 1.46 | 1.5 |
34200171 | 1.46 | 1.5 |
34200195 | 1.46 | 1.5 |
34200195 | 1.46 | 1.51 |
34200201 | 1.46 | 1.52 |
34200202 | 1.46 | 1.52 |
34200276 | 1.46 | 1.52 |
34200296 | 1.46 | 1.52 |
34200305 | 1.46 | 1.52 |
34200306 | 1.46 | 1.52 |
34200308 | 1.46 | 1.53 |
34200326 | 1.46 | 1.53 |
2
Answers
you could use a loop, but it will still be somewhat slow, but much faster than a cross join
fiddle
The following query produces the described results without doing a full cross join between table1 and table2: