SQL Server:在一个选择语句中选择多个记录 [英] SQL Server: Select multiple records in one select statement

查看:145
本文介绍了SQL Server:在一个选择语句中选择多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这样的查询中:

SELECT * 
FROM `Order`
WHERE `CustID` = '1'

我的结果显示如下:

| CustID| Order |
-----------------
| 1     | Order1|
| 1     | Order2|
| 1     | Order3|
-----------------

如何编写SQL语句,以获得类似这样的结果?:

How do I write SQL statement, to get a result like this one?:

| CustID| Order                 |
---------------------------------
| 1     | Order1, Order2, Order3|
---------------------------------

在mySQL中,可以使用Group_Concat,但是在SQL Server中,它会给出诸如语法错误之类的错误.

In mySQL it's possible with Group_Concat, but in SQL Server it gives error like syntax error or some.

推荐答案

使用xml路径(见小提琴)

SELECT distinct custid, STUFF((SELECT ',' +[order]
FROM table1 where custid = t.custid
FOR XML PATH('')), 1, 1, '')
FROM table1 t
where t.custid = 1

STUFF用空字符串替换第一个,,即将其删除.您需要一个与众不同的商品,否则,因为在哪里,所有订单都必须有一个匹配商品.

STUFF replaces the first , with an empty string, i.e. removes it. You need a distinct otherwise it'll have a match for all orders since the where is on custid.

FOR XML
PATH模式
STUFF

FOR XML
PATH Mode
STUFF

这篇关于SQL Server:在一个选择语句中选择多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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