简体   繁体   English

SQL-将具有多行的多列合并为一行

[英]SQL - Combine Multiple Columns with Multiple Rows into one row

What I'm trying to do: I have records in a SQL table where there are 5 columns and thousands of rows. 我想做的是:我在SQL表中有记录,其中有5列和数千行。 The rows share duplicate data (ie account number) but what makes each unique is that data in one of the columns is different. 这些行共享重复的数据(即帐号),但是使每个数据唯一的原因是其中一列中的数据不同。

As an example: 举个例子:

col1|col2|col3|col4|col5
------------------------
123|abc|456|def|789
123|abc|456|def|date

But the columns can have different values, not necessarily always in column 5. 但是这些列可以具有不同的值,不一定总是在第5列中。

Here's what I started with: 这是我开始的:

SELECT TOP (15) stuff((
            SELECT ', ' + te.[accountid]
                ,te.[char1]
                ,te.[date]
                ,te.[date2]
                ,te.[char2]
            FROM D AS te
            INNER JOIN D AS tue ON tue.[accountid] = te.[accountid]
            WHERE tue.[accountid] = ue.[accountid]
            FOR XML path('')
                ,type
            ).value('.', 'varchar(max)'), 1, 2, '') AS ifile
FROM D AS ue
GROUP BY ue.[accountid]

But I get a monster long string that includes the duplicate rows in one column. 但是我得到了一个怪异的长字符串,其中在一列中包含重复的行。 I'm not sure what else to try so any insight would be appreciated. 我不确定还有什么尝试的方法,因此任何见识都会受到赞赏。

If I had to guess, you have an unnecessary self join in the subquery: 如果我不得不猜测,则子查询中有不必要的自我联接:

SELECT TOP (15) stuff((
            SELECT ', ' + te.[accountid], te.[char1], te.[date], te.[date2], te.[char2]
            FROM D te
            WHERE te.[accountid] = ue.[accountid]
            FOR XML path(''), type
           ).value('.', 'varchar(max)'), 1, 2, '') AS ifile
FROM D ue
GROUP BY ue.[accountid];

You might also want SELECT DISTINCT in the subquery. 您可能还希望在子查询中使用SELECT DISTINCT

Use UNION to get rid of all the duplicate values and use your FOR XML PATH on the output to append it to a single string: 使用UNION摆脱所有重复的值,并在输出中使用FOR XML PATH将其附加到单个字符串中:

SELECT TOP (15) stuff((
            SELECT ', ' + CAST(te.[accountid] AS varchar(255)) FROM D
            UNION 
            SELECT ', ' + CAST(te.[char1] AS varchar(255)) FROM D
            UNION
            SELECT ', ' + CAST(te.[date] AS varchar(255)) FROM D
            UNION 
            SELECT ', ' + CAST(te.[date2] AS varchar(255)) FROM D
            UNION
            SELECT ', ' + CAST(te.[char2] AS varchar(255)) FROM D
            FOR XML path('')
                ,type
            ).value('.', 'varchar(max)'), 1, 2, '') AS ifile

Untested, treat as pseudo-code to give the general idea. 未经测试,将其视为伪代码以给出总体思路。

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

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