![](/img/trans.png)
[英]How to combine multiple rows into single row with different column per row's data when ID is the same
[英]How to combine multiple rows per ID into a single row for a particular column?
ID NAME INPUTS
2 ABCD First Name
2 ABCD Last Name
3 1234 First Name
3 1234 Last Name
6 QWERTY First Name
6 QWERTY Last Name
以上是Select语句返回的内容。
我希望select语句为每个ID返回最后一行“ Inputs”的行。
我当前使用的是非常基本的select语句,但是当该select语句应返回的行数少于该行数的一半时,它将返回5,000行。
declare @YourTable table (RowID int, ID int, name varchar(100), inputs varchar(500))
insert into @YourTable VALUES (1,2,'ABCD', 'First Name')
insert into @YourTable VALUES (2,2,'ABCD', 'Last Name')
insert into @YourTable VALUES (3,3,'1234', 'First Name')
insert into @YourTable VALUES (4,3,'1234','Last Name')
--insert into @YourTable VALUES (5,3,'A & Z')
set nocount off
SELECT
t1.id, t1.name
,STUFF(
(SELECT
', ' + t2.inputs
FROM @YourTable t2
WHERE t1.id=t2.id
ORDER BY t2.inputs
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
) AS inputs
FROM @YourTable t1
GROUP BY t1.id, t1.name
你可以写类似
select p.[ID], p.[First Name], p.[Last Name], isnull(p.[First Name], '') + ' ' + isnull(p.[Last Name], '') [FullName]
from
(
select t.[ID], t.[NAME], t.[INPUTS]
from [dbo].[YourTable] t
) x
pivot
(
max(x.[NAME]) for x.[INPUTS] in ([First Name], [Last Name])
) p
这将处理大多数情况:
First Name
Last Name
即使对于特殊情况也可以做一些改进
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.