【问题标题】:How to transform a row to a column and add it to the result set如何将行转换为列并将其添加到结果集中
【发布时间】:2013-11-15 12:38:39
【问题描述】:

如图所示,我有 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

我尝试了这些查询,但这些并不能解决我的问题:

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) 

【问题讨论】:

    标签: sql sql-server database join


    【解决方案1】:

    如果您的数据库是 SQL Server 2005 或更高版本,您绝对可以使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 2011-10-25
      • 2013-05-16
      • 2018-10-08
      • 1970-01-01
      相关资源
      最近更新 更多