I need to create a new table from data I extract from the following two tables:
First table:
Var cur_number
-------------------
A 10
B 8
Second table:
Var new_number
-------------------
A 2
A 11
B 4
B 6
The new table should contain a ‘Var’ column and a ‘Number’ column, where for each variable there will be one line with its cur_number, and the rest of the lines will contain the numbers from second table’s new_number columns, where the new_number < cur_number.
For example, in the example shown above, for A there will be one line with 10 (its cur_number) and one line with ‘2’ (since 2<10, however 11>10).
in my example the new table will be:
Var Number
A 10
A 2
B 8
B 4
B 6
The database is very large, and the running time is crucial so I cannot use UNION on the two tables…
Try this:Update: If you are using SQL Server 2008 or above, you can use
MERGEto merge the two tables into one like so:SQL Fiddle Demo
This will merge the two tables values into the first table. The first table will contains:
Note that: When using
MERGE:MERGEstatement with a semicolon, It is mandatory.INSERTinsideWHEN MATCHEDthats why I used the reverse condition>=in theWHEN NOT MATCHED.