2013-11-15 51 views
1

我有5個不同的表,如圖中所示。如何將行轉換爲列並將其添加到結果集中

我可以將它們結合使用該查詢,但我想添加書籍讀取日誌,使用書名作爲列名到該表中。 我用不同的顏色在圖片中顯示我的表格。

select dbo.Users.name+' '+dbo.Users.surname AS name_surname, 
     dbo.Student_Facebook_Data.likes, 
     dbo.Student_Facebook_Data.posts, 
     dbo.Student_Facebook_Data.comments, 
     dbo.Attendance.absence,dbo.Attendance.physical_presence, 
     dbo.Attendance.virtual_presence 
from dbo.Users inner join dbo.Student_Facebook_Data on dbo.Users.id=dbo.Student_Facebook_Data.student_id 
inner join dbo.Attendance on dbo.Users.id=dbo.Attendance.student_id 

我試過了查詢,但這些都沒有解決我的問題:如果你的數據庫是SQL Server 2005或更高

select dbo.Users.name+' '+dbo.Users.surname AS name_surname ,dbo.Student_Log.content_id 
from dbo.Student_Log inner join 
    dbo.Users on dbo.Student_Log.student_id=dbo.Users.id 

select distinct(material_name) 
from dbo.Material_Detail inner join 
    dbo.Student_Log on dbo.Student_Log.content_id=convert(varchar,dbo.Material_Detail.id) 

select distinct(material_name) 
from dbo.Material_Detail inner join 
    dbo.Student_Log on dbo.Student_Log.content_id=convert(varchar,dbo.Material_Detail.id) 

enter image description here

回答

0

,您可以在使用絕對不PIVOT運營商。爲了清楚起見,我只顯示如何顯示圖書的數量和使用簡化的表名:

select * from (
select u.name as 'user_name', 
     b.name as 'book_name', 
     l.id as 'reading' 
from dbo.Users u 
left join dbo.RealLog l on u.id = l.user_id 
left join dbo.Books b on l.bid = b.id 
) x 
pivot (count(reading) for book_name in ([one],[two],[three],[four],[five])) as count 

PIVOT參考:http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

相關問題