我有表:
name quantity
abc 2
abc 3
abc 5
我如何在 mssql 中查询以查看一行中的结果,例如
abc 2 3 5
谢谢。
如果您希望此数据位于单独的列中,则可以使用以下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 PATH
and STUFF()
:
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)