I have a table A looks like :
id isin typ1 typ2
1 aa typA typB
2 bb typD typC
I need to insert into a table B that looks like:
id isin fld value
1 aa typ1 typA
2 aa typ2 typB
3 bb typ1 typD
4 bb typ2 typC
Can I do with an SQL instruction?
The most generic approach is union all
:
insert into tableb (id, isin, fld, value)
select id, isin, 'typ1', typ1 from tablea
union all select id, isin, 'typ2', typ2 from tablea
If your database, which you did not disclose, supports lateral joins, this can be more efficiently done using this feature. A typical syntax would be:
insert into tableb (id, isin, fld, value)
select a.id, a.isin, x.fld, x.value
from tabla a
cross join lateral (values ('typ1', typ1), ('typ2', typ2)) as x(fld, value)
The exact syntax for lateral joins varies across databases.
You can use ROW_NUMBER()
Analytic function along with UNION ALL
in order to insert the values unpivoted and id values renumerated
INSERT INTO tableB(id, isin, fld, value)
SELECT ROW_NUMBER() OVER (ORDER BY isin, fld), A.*
FROM
(
SELECT isin, 'typ1' AS fld, typ1 AS typ FROM tableA UNION ALL
SELECT isin, 'typ2' , typ2 FROM tableA
) AS A
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.