2015-05-09 96 views
-1

我的數據庫表轉換我行插入列數據列到行中的SQL Server

StudId Day1 Day2 Day3 Day4 Day5 
------------------------------- 
1  P P P P P 
2  A P P P P 
3  P A P A P 
4  A P P P P 

我多麼希望我的數據是每個studentId

 1 
Day1 P 
Day2 P 
Day3 P 
Day4 P 
Day5 P 

我怎樣才能做到這一點情景?請幫助....

回答

0

使用'union all'爲每列:

假設結果列將被稱爲'col1',而不是'1'

Select Day1 as 'col1' 
From table 
Where StudId = 1 

Union all 

select Day2 as 'col1' 
From table 
Where StudId = 1 

--and so on 
0

嘗試,

declare @tb table (StudId int, Day1 char, Day2 char, Day3 char, Day4 char, Day5 char) 
insert into @tb (StudId, Day1, Day2, Day3, Day4, Day5) values 
(1,'P','P','P','P','P'), 
(2,'A','P','P','P','P'), 
(3,'P','A','P','A','P'), 
(4,'A','P','P','P','P') 
select cat,[1],[2],[3],[4] from(

select t.* from @tb cross apply(values (StudId,Day1,'day1'),(StudId,Day2,'day2'),(StudId,Day3,'day3'),(StudId,Day4,'day4'),(StudId,Day5,'day5')) t (StudId,value,cat)) t 
pivot 
(min(value) for studid in ([1],[2],[3],[4]) 
)pvt