简体   繁体   English

如何在单选查询中将行转换为列SQL Server 2008 R2

[英]How To Convert Rows Into Column In Single Select Query SQL Server 2008 R2

How to return the following result on single select query. 如何在单查询中返回以下结果。

Table

Rn  TicketNo    CreateDate               Assigned
1   xxx         2016-11-17 03:45:46.000  Tom
2   xxx         2016-11-18 03:45:46.000  Jerry
1   yyy         2016-11-17 03:45:46.000  Tom
2   yyy         2016-11-18 03:45:46.000  Jerry

Expected Result 预期结果

TicketNo    AssignedToTom             AssignedToJerry
xxx         2016-11-17 03:45:46.000  2016-11-18 03:45:46.000
yyy         2016-11-17 03:45:46.000  2016-11-18 03:45:46.000

Many thanks in advance 提前谢谢了

Try This: replace with name of your table 试试这个:用表格名称替换

select a.ticketno
        ,a.CreateDate as [AssignedToTom]
        ,b.CreateDate as [AssignedToJerry]
         from <tablename> a join <tablename> b 
         on a.assigned='Tom' and b.assigned='Jerry' 
         and a.ticketno=b.ticketno

Try Below Pivot Query. 尝试以下枢轴查询。 Simply replace table name '#temp' to Your 'table name' 只需将表名“ #temp”替换为“表名”

            select distinct  TicketNo,Tom as AssignedToTom,Jerry as AssignedToJerry
            from
            (
               select distinct TicketNo,CreateDate,Assigned 
               from #temp
            ) src
            pivot
            (
              max(CreateDate)
              for Assigned in (Tom, Jerry)
            ) piv
select ticketno,
       MAX(case when Assigned='Tom' 
                then createddate else null END) as AssignedToTom,
       MAX(case when Assigned='Jerry' 
                then createddate else null END) as AssignedToJerry
from yourtab
group by ticketno
Select 
     TicketNo 
    ,(Select CreateDate from TicketDtl where TicketNo= A.TicketNo and Assigned='Tom')as AssignedToTom
    ,(Select CreateDate from TicketDtl where TicketNo= A.TicketNo and Assigned='Jerry') as AssignedToJerry
From TicketDtl as A
Group by TicketNo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM