SQL:如何将表列显示为行?

时间:2013-02-28 15:25:32

标签: sql-server join

我有桌子:

name quantity
abc     2
abc     3
abc     5

如何在mssql中查询以查看一行中的结果,例如

abc 2 3 5

感谢。

1 个答案:

答案 0 :(得分:4)

如果您希望将这些数据放在不同的列中,则可以使用PIVOT函数:

select *
from 
(
  select name, quantity,
    'Qty_'+cast(row_number() over(partition by name order by quantity) as varchar(10)) rn
  from yourtable
) src
pivot
(
  max(quantity)
  for rn in (Qty_1, Qty_2, Qty_3)
) piv

SQL Fiddle with Demo。枢轴的结果是:

| NAME | QTY_1 | QTY_2 | QTY_3 |
--------------------------------
|  abc |     2 |     3 |     5 |

如果您希望将这些数据放在一个列中,那么您可以使用FOR XML PATHSTUFF()

SELECT
     t1.Name,
     STUFF(
         (SELECT ' ' + cast(quantity as varchar(10))
          FROM yourtable t2
          WHERE t1.name = t2.name
          FOR XML PATH (''))
          , 1, 1, '')  AS List
FROM yourtable t1
GROUP BY t1.Name

SQL Fiddle with Demo。此查询的结果是:

| NAME |  LIST |
----------------
|  abc | 2 3 5 |

使用pivot功能,如果您有未知数量的数值,那么您可以使用动态sql:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(rn) 
                    from
                    (
                      select 'Qty_'+cast(row_number() over(partition by name order by quantity) as varchar(10)) rn
                      from yourtable
                    ) t
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT name,' + @cols + ' from 
             (
                select name, quantity,
                  ''Qty_''+cast(row_number() over(partition by name order by quantity) as varchar(10)) rn
                from yourtable
            ) x
            pivot 
            (
                max(quantity)
                for rn in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with Demo