user2645263
user2645263

Reputation: 31

SQL, questions about join

I have two tables in sql 2012: name and prod with structure:

name: id int increment, name1 nvarchar(50)

prod: id int increment, products nvarchar(50), id_name int

Values for table are:

name table:

Id   name1
1    pop
2    andi

prod table:

Id   products   id_name
1    coke       1
2    pizza      1
3    orange     2

I have done this query:

select name.name1, prod.product, prod.id_name
from name
join prod on name.id=prod.id_name

How can I obtain this result:

pop ->coke, pizza
andi->orange  

Upvotes: 2

Views: 190

Answers (3)

MrSimpleMind
MrSimpleMind

Reputation: 8627

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

Upvotes: 3

roman
roman

Reputation: 117550

unfortunately, there's no easy way to do it in SQL Server. Known solutions are:

  • xml trick (see below);
  • using variable to accumulate data (don't work for multiple group rows, only with cursor);
  • custom CLR aggregate;

here's 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

here's variable:

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

Upvotes: 5

Joe Taras
Joe Taras

Reputation: 15399

try this:

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

Upvotes: 3

Related Questions