Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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  
like image 914
user2645263 Avatar asked Sep 27 '26 17:09

user2645263


2 Answers

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

like image 172
Roman Pekar Avatar answered Sep 29 '26 11:09

Roman Pekar


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
like image 38
Joe Taras Avatar answered Sep 29 '26 12:09

Joe Taras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!