sql server - query for retrieving information from 3 tables in sql? -


i have 3 tables

1) news_table nid     tilte 1       hi 2       hello  2) product_table  pid     name  2       abc   3       def   4       rty   5       zxc   6       poj   7       lkj    3) temp nid     pid  1       2   1       3   1       4   2       5   2       6   2       7   

i want output

nid     pids    names           title   1       2,3,4   abc,def,rtj     hi  2       5,6,7   zxc,poj,lkj     hello 

this full working example run on sql server 2012:

declare @news_table table (     [nid] tinyint    ,[title] varchar(8) );  insert @news_table ([nid], [title]) values (1, 'hi')       ,(2, 'hellow');  declare @product_table table (     [pid] tinyint    ,[name] varchar(8) );  insert @product_table ([pid], [name]) values (2, 'abc')       ,(3, 'def')       ,(4, 'rty')       ,(5, 'zxc')       ,(6, 'poj')       ,(7, 'lkj');  declare @temp table (    [nid] tinyint   ,[pid] tinyint );  insert @temp ([nid], [pid]) values (1, 2)       ,(1, 3)       ,(1, 4)       ,(2, 5)       ,(2, 6)       ,(2, 7);  select [nid]       ,[pids]       ,[names]       ,[title] @news_table nt cross apply (     select stuff     (         (             select ',' + pt.[name]             @temp t             inner join @product_table pt                 on t.[pid] = pt.[pid]             t.[nid] = nt.[nid]             xml path(''), type         ).value('.', 'nvarchar(max)')         ,1         ,1         ,''     ) ) ds1 ([names]) cross apply (     select stuff     (         (             select ',' + cast(t.[pid] varchar(12))             @temp t             t.[nid] = nt.[nid]             xml path(''), type         ).value('.', 'varchar(max)')         ,1         ,1         ,''     ) ) ds2 ([pids]); 

enter image description here


i recommend check following links .net integration in sql server:

you can defined own aggregates. example, concatenating strings , solution far more simple:

select nt.[nid]       ,[dbo].[concatenate] (t.[pid]) [pids]       ,[dbo].[concatenate] ([name]) [names]       ,nt.[title] @news_table nt inner join @temp t     on t.[nid] = nt.[nid] inner join @product_table pt     on t.[pid] = pt.[pid] group nt.[nid]         ,nt.[title] 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -