SQL,关于加入的问题

时间:2013-08-20 12:32:46

标签: sql sql-server-2008 tsql

我在sql 2012中有两个表:name和prod with structure:

名称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  

3 个答案:

答案 0 :(得分:5)

不幸的是,在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

sql fiddle demo

这是变量:

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 fiddle demo

答案 1 :(得分:3)

试试这个:

SELECT
G.id,
G.name1,
stuff(
    (select cast(',' as varchar(10)) + U.product
    from prod U
    WHERE U.id_name = G.id
    order by U.product
    for xml path('')
), 1, 1, '') AS prod
FROM name G
ORDER BY G.name1 ASC

答案 2 :(得分:3)

sqlfiddle

select
n.nameid [id],
n.name [name],
count(*)[count],
    stuff(
        (
         select ', ' + p.prod
         from prodtbl as p
         where p.nameid = n.nameid
         for xml path(''),  type).value('.', 'nvarchar(max)'), 1, 1, '') as products
from nametbl n, prodtbl p
where p.nameid = n.nameid
group by n.nameid, n.name
order by [id];

enter image description here