Solved

SQL Query Help

Posted on 2010-11-10
4
286 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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

As they say in love and is true in SQL: you can sum some Data some of the time, but you can't always aggregate all Data all the time! Introduction: By the end of this Article it is my intention to bring the meaning and value of the above quote to…
Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

860 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