Compte tenu du scénario suivant:
create table vertical(
CustomerID int,
attribute varchar(255),
value varchar(255)
)
create table horizontal(
CustomerID int,
name varchar(255),
surname varchar(255),
phone varchar(255)
)
insert into vertical
select 30, 'Name', 'John'
insert into vertical
select 30, 'Surname', 'Smith'
insert into vertical
select 30, 'Phone', '551123456'
insert into vertical
select 40, 'Name', 'Mary'
insert into vertical
select 40, 'Surname', 'Johnson'
insert into vertical
select 40, 'Phone', '9991111234'
insert into vertical
select 50, 'Surname', 'Manuel'
insert into vertical
select 50, 'Phone', '423'
exécutant cet insert sortie doit
insert into horizontal (CustomerID, name, surname, phone)
select c.CustomerID, n.value as name, s.value as surname, ph.value as phone
from
(select distinct CustomerID from vertical) as c
left join vertical n
on c.CustomerID = n.CustomerID and n.attribute = 'name'
left join vertical s
on c.CustomerID = s.CustomerID and s.attribute = 'Surname'
left join vertical ph
on c.CustomerID = ph.CustomerID and ph.attribute = 'Phone'
ceci:
ID Name Surname Phone
-- ---- ------- -----
30 John Smith 551123456
40 Mary Johnson 9991111234
50 NULL Manuel 423
Où:
de:select distinct CustomerID from vertical
apporte tous les clients qui ont au moins un attribut. Chaque jointure à gauche renvoie la valeur correspondante pour chaque attribut.
La jointure à gauche a été utilisée pour s'assurer que la ligne client sera insérée même s'il manque des attributs au client, auquel cas NULL sera inséré.
table source nommée verticale est celle avec les valeurs d'attribut
table cible horizontale nommée est votre sortie désirée
Merci beaucoup! C'est une réponse dont je n'aurais même pas rêvé! – kubal5003