将2行数据合并为1

时间:2012-11-11 04:34:17

标签: row pivot

我有一个非常复杂的查询。我希望2行数据合并为1行。

它给了我以下输出

         PNAME    RN         LVN        HA         MSW       SC
           AA     AG-1W      SS-1M     LO-2W      PA-1W      SK-1M
           AA     JL-1W      TD -1M     NULL      NULL       NULL

有没有什么方法可以将结果放在1行或将2行合并到1.如同跟随。

            PNAME      RN         LVN        HA        MSW         SC
             AA       AG-1W      SS-1M     LO-2W      PA-1W      SK-1M
                      JL-1W      TD -1M     NULL       NULL       NULL

1 个答案:

答案 0 :(得分:1)

目前尚不清楚您要实现的目标,但您可以实施row_number()的使用,以防止pname显示在其他行中:

select case when rownum = 1 then pname else '' end pname, 
    [RN], [LVN], [HA], [MSW], [SC]
from
(
    select pname, disc, value,
        ROW_NUMBER() over(partition by disc order by disc) rownum
    from temp
) src
pivot
(
    max(value)
    for disc in ([RN], [LVN], [HA], [MSW], [SC])
) piv

请参阅SQL Fiddle with demo

结果:

| PNAME |    RN |   LVN |     HA |    MSW |     SC |
----------------------------------------------------
|    AA | AG-1W | SS-1M |  LO-2W |  PA-1W |  SK-1M |
|       | JL-1W | TD-1M | (null) | (null) | (null) |

这使用row_number()的值来决定是否应显示pname。它只显示rownum=1时的值,否则显示为空白。

如果您希望将数据放在一行中,则可以使用类似于以下内容的内容:

;with cte as
(
  select pname, disc, value,
    ROW_NUMBER() over(partition by disc order by disc) rownum
  from temp
),
piv as 
(
  select * 
  from cte
  pivot
  (
    max(value)
    for disc in ([RN], [LVN], [HA], [MSW], [SC])
  ) piv
)
select pname,
  STUFF((SELECT distinct ', ' + [RN]  
              from piv p2
              where p1.pname = p2.pname
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') RN,
  STUFF((SELECT distinct ', ' + [LVN]  
              from piv p2
              where p1.pname = p2.pname
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') LVN,
  STUFF((SELECT distinct ', ' + [HA]  
              from piv p2
              where p1.pname = p2.pname
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') HA,
  STUFF((SELECT distinct ', ' + [MSW]  
              from piv p2
              where p1.pname = p2.pname
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') MSW,   
  STUFF((SELECT distinct ', ' + [SC]  
              from piv p2
              where p1.pname = p2.pname
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') SC   
from piv p1
group by pname

请参阅SQL Fiddle with Demo

结果是:

| PNAME |            RN |           LVN |     HA |    MSW |     SC |
--------------------------------------------------------------------
|    AA |  AG-1W, JL-1W |  SS-1M, TD-1M |  LO-2W |  PA-1W |  SK-1M |