I need to insert data in one table into another table. Basically I need to do this:
INSERT INTO Consulta (tipo, busqueda1, resultado1, resultado2, resultado3)
The value of the field tipo
is defined by me, but the values of the other fields are extracted from the following query:
SELECT CODIGO_USUARIO, Electrodomestico, Cant FROM (SELECT CODIGO_USUARIO, [Abanico Mesa], [Abanico Techo], [Estufa Elect 1F] FROM TempCensoElect) p UNPIVOT (Cant FOR Electrodomestico IN ([Abanico Mesa], [Abanico Techo], [Estufa Elect 1F])) AS unpvt
Resulting in the following:
The column data CODIGO_USUARIO
must be inserted into the fields busqueda1, resultado1
. The column data Electrodomestico
must be inserted into the field resultado2
and the column data Cant
must be inserted into the fieldresultado3
How can I do this?
The values returned from your select must have the same order and number of columns inserted in your insert .
I see 1 problem in your logic:
You are inserting type, but you don't have any value to insert type in your select, if you are not going to extract it then remove it from your insert or add some value to your query
Outside of that you just need to add an alias for the user_code field to be able to be inserted in two fields
Reference :
The query would look something like this: