7
Mam problem z wyjściem z pivota. Potrzebuję go w mojej pożądanej formie do tabel koherencji.Dynamic pivot w SQL Server
Mój wynik:
us_id Phone Mail
1 555121313 NULL
1 NULL [email protected]
2 14124124 NULL
2 NULL [email protected]
Pożądany wyjściowa:
us_id Phone Mail
1 555121313 [email protected]
2 14124124 [email protected]
Script dla testu:
create table #user (us_id int, us_login varchar(255))
INSERT INTO #user VALUES (1, 'LoginOne')
INSERT INTO #user VALUES (2, 'LoginTwo')
create table #atr_type (at_id int, at_name varchar(255))
insert into #atr_type values (1,'Phone');
insert into #atr_type values (2,'Mail')
create table #atr (atr_id int, atr_us_id int, atr_at_id int, atr_value varchar(255))
insert into #atr values(1,1,1,'555121313')
insert into #atr values(2,1,2,'[email protected]')
insert into #atr values(3,2,1,'14124124')
insert into #atr values(4,2,2,'[email protected]')
Mój kod do dynamicznego przegubu:
DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N',' + QUOTENAME(at_name)
FROM ( SELECT at_name
FROM #atr_type) AS x;
select @columns
declare @cmd varchar(max)
set @cmd = '
SELECT us_id'+[email protected]+'
FROM #user inner join #atr on atr_us_id = us_id
inner join #atr_type on at_id = atr_at_id
PIVOT (
MIN(atr_value) FOR at_name IN
('
set @columns = RIGHT(@columns, LEN(@columns)-1)
set @cmd += @columns + ')
) AS PT'
exec (@cmd)
+1 trochę późno z moją odpowiedź. –