简体   繁体   English

如何将每个ID的多行合并为特定列的一行?

[英]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

Above is what the Select statement returns. 以上是Select语句返回的内容。

I would like the select statement to return one row per ID combining the last column "Inputs". 我希望select语句为每个ID返回最后一行“ Inputs”的行。

I currently am using a very basic select statement but this select statement is returning over 5,000 rows when it should be returning less than half of that number. 我当前使用的是非常基本的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

You could write something like 你可以写类似

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

This will handle most cases: 这将处理大多数情况:

  • No First Name 没有First Name
  • No Last Name 没有Last Name
  • No name at all 完全没有名字

Even though some improvements can be done for special cases 即使对于特殊情况也可以做一些改进

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

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