我在 sql 2012 中有两个表:name 和 prod 结构:
名称:id int increment, name1 nvarchar(50)
prod:id int increment, products nvarchar(50), id_name int
表的值是:
名称表:
Id name1
1 pop
2 andi
产品表:
Id products id_name
1 coke 1
2 pizza 1
3 orange 2
我已经完成了这个查询:
select name.name1, prod.product, prod.id_name
from name
join prod on name.id=prod.id_name
我怎样才能得到这个结果:
pop ->coke, pizza
andi->orange
最佳答案
不幸的是,在 SQL Server 中没有简单的方法可以做到这一点。已知的解决方案是:
- xml 技巧(见下文);
- 使用变量累积数据(不适用于多组行,仅适用于游标);
- 自定义 CLR 聚合;
这是 xml:
select
n.name1,
stuff(
(
select ', ' + p.product
from prod as p
where p.id_name = n.id
for xml path(''), type).value('.', 'nvarchar(max)')
, 1, 2, '') as products
from name as n
这是变量:
declare @product nvarchar(max), @id int
select @id = 1
select @product = isnull(@product + ', ', '') + product
from prod
where id_name = @id
select name1, @product as products
from name
where id = @id
关于SQL,关于join的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18335157/