一组行的 MS SQL 上的字符串连接 [英] String concat on MS SQL for a group of rows

查看:18
本文介绍了一组行的 MS SQL 上的字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 2 张桌子:

1 与用户另一个记录哪些用户使用了哪些代码.

<上一页>用户-----身份证、姓名1,约翰"2,母鹿"代码------标识、用户标识、代码1, 1, 1452, 1, 1873, 2, 251

现在我想提取一个导致他关注的查询

<上一页>名称,使用的代码'约翰','145,187''Doe','251'

如何通过查询或存储过程来做到这一点?

解决方案

既然你还没有指定数据库,我给你两个选择:

MySql

使用 MySql 你应该简单地使用 GROUP_CONCAT() 聚合函数.

Microsoft SQL Server 2005+

显然,在 MS DB 上获得相同结果的 最快方式(无游标、无合并...)是使用 FOR XML PATH('')只是省略了 XML 元素.

选择你的名字,c1.UserId,(选择 c2.代码 + ','来自代码 c2其中 c2.UserId = c1.UserId由 c2.code 订购用于 XML 路径('')) 作为代码从代码 c1加入用户你开(u.Id = c1.UserId)GROUP BY c1.UserId, u.Name

其他选择

阅读这篇文章,它解释了实现这一目标的所有可能方法.

Lets say I have 2 tables:

1 with users and another one which keeps record of which users used what codes.

Users
-----
Id, Name
1, 'John'
2, 'Doe'

Codes
------
Id, UserId, code
1, 1, 145
2, 1, 187
3, 2, 251

Now I want to pull a query that results he following

Name, UsedCodes
'John', '145,187'
'Doe', '251'

How can this be done with a query or stored procedure?

解决方案

Since you haven't specified the DB I'm giving you two options:

MySql

With MySql you should simply use GROUP_CONCAT() aggregate function.

Microsoft SQL Server 2005+

Obviously the fastest way (no cursors, no coalesce...) of getting the same result on MS DB is by using FOR XML PATH('') that simply omits XML elements.

SELECT
    u.Name,
    c1.UserId,
    (
        SELECT c2.Code + ','
        FROM Codes c2
        WHERE c2.UserId = c1.UserId
        ORDER BY c2.code
        FOR XML PATH('')
    ) as Codes
FROM Codes c1
    JOIN Users u
    ON (u.Id = c1.UserId)
GROUP BY c1.UserId, u.Name

Other alternatives

Read this article, that explains all the possible ways of achieving this goal.

这篇关于一组行的 MS SQL 上的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆