Solved

SQL Query Help

Posted on 2010-11-10
4
280 Views
Last Modified: 2012-05-10
SQL Server 2005 table:

ID   NewID
01    A01
02    A02
03   A031
03   A032
03   A033
03   A034
04   A041
04  A04 etc.  (NewId is unique)

Desired output:
ID  NewID1 NewID2 NewID3 NewID4 NewID5
01    A01
02    A02
03   A031    A032    A033     A034
04   A041      A04

Do I have to set in advance how many NewID columns are in the output?
Can it be dynamic?

Thank you very much!

0
Comment
Question by:larisa1970
4 Comments
 
LVL 8

Expert Comment

by:kingjely
ID: 34108924


Hi Larisa
In mysql this would do what you need.. I'm not sure if it will work in mssql but worth a go

SELECT ID, GROUP_CONCAT(NEWID)
FROM YOURTABLE
GROUP BY ID
0
 
LVL 2

Expert Comment

by:marat-oz
ID: 34110131
try this, but number of possible NEWIDs is hardcoded

WITH T (ID, [NEWID], GID)
AS
(
select *, row_number() over (partition by ID order by ID, [NewID])
from <YourTable>
)
select t1.ID, COALESCE(NEWID1,'') NEWID1, COALESCE(NEWID2,'') NEWID2, COALESCE(NEWID3,'') NEWID3, COALESCE(NEWID4,'') NEWID4, COALESCE(NEWID5,'') NEWID5
from  
(select ID, NEWID1 = [NewID] from T where t.GID = 1) t1
LEFT JOIN
(select ID, NEWID2 = [NewID] from T where t.GID = 2) t2 on t1.ID = t2.ID
LEFT JOIN
(select ID, NEWID3 = [NewID] from T where t.GID = 3) t3 on t1.ID = t3.ID
LEFT JOIN
(select ID, NEWID4 = [NewID] from T where t.GID = 4) t4 on t1.ID = t4.ID
LEFT JOIN
(select ID, NEWID5 = [NewID] from T where t.GID = 5) t5 on t1.ID = t5.ID

0
 
LVL 6

Expert Comment

by:dan_mason
ID: 34110952
This will give you the number of columns needed, and create them...
DECLARE @numCol int, @counter int=1, @sql varchar(200)
CREATE TABLE #output (ID char(2))
DECLARE @input table (ID char(2),NewID varchar(5))
INSERT @input (ID,NewID)
VALUES
('01','A01'),('02','A02'),('03','A031'),('03','A032'),('03','A033'),('03','A034'),('04','A041')

INSERT #output (ID)
SELECT DISTINCT ID FROM @input

SELECT @numCol= MAX(n) FROM(SELECT(COUNT(1)) as n FROM @input GROUP BY ID) a

WHILE @counter<=@numCol
	BEGIN
		SET @sql='ALTER TABLE #output ADD NewID'+CAST(@counter as varchar)+' varchar(5)'
		EXEC (@sql)
		SET @counter=@counter+1
	END

SELECT * FROM #output
DROP TABLE #output

Open in new window

0
 
LVL 41

Accepted Solution

by:
ralmada earned 500 total points
ID: 34112243
You don't have to ALTER your table to do that.
I assume you don't know how many NewID you will have there per ID correct so basically you don't know how many columns you will need. Hence, you have to go with dynamic SQL. Check the below:

declare @strSQL varchar(max)

declare @cols varchar(max)



set @cols = stuff((select distinct 

			'], [' + cast(row_number() over (partition by id order by [NewID]) as varchar)

		from yourtable

		for xml path('')), 1, 2, '') + ']'



set @strSQL = 	' select id, ' + @cols +

		' from (select	id, 

				[NewID],

				row_number() over (partition by ID order by NewID) rn

			from yourtable

		 ) o

		pivot (max([NewID]) for rn in (' + @cols + ')) p'



exec(@strSQL)

Open in new window

0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Confronted with some SQL you don't know can be a daunting task. It can be even more daunting if that SQL carries some of the old secret codes used in the Ye Olde query syntax, such as: (+)     as used in Oracle;     *=     =*    as used in Sybase …
PL/SQL can be a very powerful tool for working directly with database tables. Being able to loop will allow you to perform more complex operations, but can be a little tricky to write correctly. This article will provide examples of basic loops alon…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now