简体   繁体   English

如何连接一列的所有条目[SQL]

[英]How to concat all the entries of one column [SQL]

As the title states, with the following SQL query:正如标题所述,使用以下 SQL 查询:

SELECT "Name"
FROM "ExampleTable"

I get the following result:我得到以下结果:

Name
----------------
ExampleName1
ExampleName2
ExampleName3

Question: how to modify the query so that all the names are to be displayed in a row, so that they can be later used an array.问题:如何修改查询使所有名称都显示在一行中,以便以后可以使用数组。

What I tried: FOR XML , STUFF - doesn't work我试过的: FOR XML , STUFF - 不起作用

Expected result:预期结果:

Name: ExampleName1, ExampleName2, ExampleName3.

If you are using SQL Server you can try this:如果您使用的是 SQL Server,您可以试试这个:

Select SUBSTRING( 
( 
     SELECT ',' + Name AS 'data()'
         FROM TableName FOR XML PATH('') 
), 2 , 1000) As Names

Check this on Fiddle: http://sqlfiddle.com/#!18/6ab0b3/6在 Fiddle 上检查一下: http ://sqlfiddle.com/#!18/6ab0b3/6

Or may be an easy way using COALESCE that combines the multiple rows in single row separated by Comma separated values based on parameters passed:或者可能是使用COALESCE一种简单方法,它根据传递的参数组合由逗号分隔值分隔的单行中的多行:

Declare @val Varchar(MAX); 
Select @val = COALESCE(@val + ', ' + Name, Name) 
        From TableName Select @val;

select @val; // this will show all your data

Check this on fiddle: http://sqlfiddle.com/#!18/36112/2在小提琴上检查这个: http ://sqlfiddle.com/#! 18/36112/2

Also, I am giving the screenshots for you to easily understand the steps if something goes wrong with the above screenshots.此外,如果上述屏幕截图出现问题,我将提供屏幕截图供您轻松理解步骤。

Please note: In the above process, neither I have taken any PRIMARY KEY nor I am setting its auto-increment, but in the upcoming explanation I have used PRIMARY KEY as I have written everything in SSMS (Sql Server Management Studio)请注意:在上面的过程中,我既没有使用任何 PRIMARY KEY 也没有设置它的自动增量,但在接下来的解释中,我使用了 PRIMARY KEY,因为我已经在 SSMS (Sql Server Management Studio) 中编写了所有内容

Here is the schema for sample tblStudent table with PRIMARY KEY and auto increment set as you can see below:这是带有 PRIMARY KEY 和自动增量集的示例tblStudent表的架构,如下所示:

在此处输入图片说明

Next enter some dummy values in it接下来在其中输入一些虚拟值

在此处输入图片说明

finally write our query.最后编写我们的查询。

在此处输入图片说明

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

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