2016-11-17 31 views
0

變化值的數目我有一個情況我需要值轉換成一排源表顯示爲COLUMN_NAMES和創造在target.I這些列的動態case語句有這個下面的示例查詢做那(1/2方式)。我的問題是,我可能會在源行2CODES或3CODES或5CODES以上的價值觀和我的目標表結構(沒有列)應該像明智的創建。創建從源

請幫我解決任何用於動態創建基於源值無列。我曾嘗試下面的情況下語句,並試圖看到的,我們可以使用最大/最小功能上ROW_NUMBER來解決這個問題(只是盲目的思想)

請指點。

如:

源表SSS

NAME ID CODE 
AAA  1 XXX 
BBB  2 YYY 
CCC  3 PPP 
AAA  1 YYY 
AAA  1 PPP 

目標:TGT

NAME ID XXX YYY PPP 
AAA 1 A A  A 
CCC 3 N N  A 
BBB 2 N A  N 

從單排多個值轉換爲多列對於給定的ID

這是什麼我試過了:

insert into fat 
select id, 
     max(case when rownum = 1 then val else '' end), 
     max(case when rownum = 2 then val else '' end), 
     max(case when rownum = 3 then val else '' end), 
     max(case when rownum = 4 then val else '' end) 
from long_ordered 
group by id 


select * from fat 



select id, va11 as val from fat 
union all select id, va12 from fat 
union all select id, va13 from fat 
union all select id, va14 from fat 

回答

0

要做到這一點,你需要使用動態SQL和光標。請參閱下面的完整解釋示例。

請注意,我用的動態SQL基於什麼在SSS表創建TGT表。然後使用遊標遍歷SSS表,併爲SSS中的每個記錄更新TGT表。更新只爲'A'條目完成,其他所有設置都使用默認設置爲'N'。

create table SSS(Name varchar(3), ID int, Code varchar(3)) 
insert into SSS values 
('AAA' , 1 , 'XXX'), 
('BBB' , 2 , 'YYY'), 
('CCC' , 3 , 'PPP'), 
('AAA' , 1 , 'YYY'), 
('AAA' , 1 , 'PPP'); 


--get a list of columns based on code field 
declare @columns nvarchar(max) = (select distinct N'[' + code + N'] char(1) null default ''N'',' from sss for xml path('')); 
--remove trailing comma 
set @columns = LEFT(@columns, LEN(@Columns) - 1); 

--declare dynamic sql command variable 
declare @cmd nvarchar(max); 
--populate command with SQL to create a table 
set @cmd = N'CREATE TABLE TGT(Name varchar(3) not null, ID int not null, ' + @columns + ');'; 
--show command (for troubleshooting only) 
select @cmd; 

--execute command to create a new table. 
exec sp_executesql @cmd; 
go 

--prepare the table by inserting the names and ids 
insert into tgt(name, id) 
select distinct name, id 
from sss; 
go 

--declare variables 
declare @name varchar(3), @id int, @code varchar(3); 
declare @cmd nvarchar(max); 

--declare cursor to iterate through sss 
declare cur cursor fast_forward for 
select name, id, code 
from sss; 

open cur; 

fetch next from cur into @name, @id, @code; 

--main loop 
while (@@FETCH_STATUS = 0) 
BEGIN 
    set @cmd = 'UPDATE tgt SET ' + @code + ' = ''A'' WHERE [name] = ''' + @name + ''' and [id] = ' + cast(@id as varchar(5)) + ';'; 
    exec sp_executesql @cmd; 
    fetch next from cur into @name, @id, @code; 
END 


close cur; 
deallocate cur; 
go 

select * from tgt;