Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
rammohan
Posting Yak Master
212 Posts |
Posted - 2008-10-20 : 10:02:54
|
| Hi,My Table structure is:Table 3:ID SID BID1 1 11 1 21 1 3Table2:SID SNAME1 RamTable1:BID BNAME1 King2 Tiger3 Lioni want to construct a query which will produce op like thisID SNAME BNAME1 Ram King,Tiger,LionPlease Show me a wayOne can never consent to creep,when one feels an impulse to soarRAMMOHAN |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2008-10-20 : 10:14:45
|
[code]DECLARE @Table3 TABLE ( ID INT, SID INT, BID INT )INSERT @Table3SELECT 1, 1, 1 UNION ALLSELECT 1, 1, 2 UNION ALLSELECT 1, 1, 3DECLARE @Table2 TABLE ( SID INT, SNAME SYSNAME )INSERT @Table2SELECT 1, 'Ram'DECLARE @Table1 TABLE ( BID INT, BNAME SYSNAME )INSERT @Table1SELECT 1, 'King' UNION ALLSELECT 2, 'Tiger' UNION ALLSELECT 3, 'Lion';WITH Yak (ID, SNAME, BNAME)AS ( SELECT t3.ID, t2.SNAME, t1.BNAME FROM @Table3 AS t3 INNER JOIN @Table2 AS t2 ON t2.SID = t3.SID INNER JOIN @Table1 AS t1 ON t1.BID = t3.BID)SELECT d.ID, d.SNAME, STUFF(w.f, 1, 1, '') AS BNAMEFROM ( SELECT ID, SNAME FROM Yak GROUP BY ID, SNAME ) AS dCROSS APPLY ( SELECT DISTINCT ',' + y.BNAME FROM Yak AS y WHERE y.ID = d.ID AND y.SNAME = d.SNAME ORDER BY ',' + y.BNAME FOR XML PATH('') ) AS w(f)[/code] E 12°55'05.63"N 56°04'39.26" |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-10-20 : 10:17:08
|
| [code];With Yak (BNAME,SNAME) AS(SELECT t1.BNAME,t2.SNAMEFROM Table1 t1INNER JOIN Table3 t3On t3.BID=t1.BIDINNER JOIN Table2 t2ON t2.SID=t3.SID)SELECT t1.SNAME,LEFT(nl.namelist,LEN(nl.namelist)-1)FROM (SELECT DISTINCT SNAME FROM Yak) t1CROSS APPLY(SELECT BNAME +',' FROM Yak WHERE SNAME=t1.SNAME FOR XML PATH('')) nl(namelist)[/code] |
 |
|
|
rammohan
Posting Yak Master
212 Posts |
Posted - 2008-10-20 : 10:19:28
|
| Can u please tell me what is that Yak? is it a predefined function?One can never consent to creep,when one feels an impulse to soarRAMMOHAN |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-10-20 : 10:21:59
|
quote: Originally posted by rammohan Can u please tell me what is that Yak? is it a predefined function?One can never consent to creep,when one feels an impulse to soarRAMMOHAN
Nope its called CTE (Common Table Expressions). its like derived table. look into syntax of CTE in books onlinehttp://msdn.microsoft.com/en-us/library/ms190766.aspx |
 |
|
|
rammohan
Posting Yak Master
212 Posts |
Posted - 2008-10-20 : 10:29:19
|
| Thank uOne can never consent to creep,when one feels an impulse to soarRAMMOHAN |
 |
|
|
|
|
|
|
|