January 24, 2008 at 5:17 am
Hi there
I'm sure this is easy but I'm battling with it, anyway this is what I would like to achieve.
I have a very badly designed table such that there are recordIDs and Keys, recordIDs may be duplicated, keys are unique ie : -
RecordID Key
1234 23
2345 45
2345 46
2345 47
9876 90
9876 91
I wish to 'flatten' the data out so I can return the following recordset : -
1234 23
2345 45 46 47
9876 90 91
Can someone point me in the right direction please, I'm on SQL server 2005
Many thanks - Martin
January 24, 2008 at 5:31 am
It's not clear whether you want the keys concatenated into one column or left as separate columns.
This will concatentate the keys
SELECT a.RecordID,
(SELECT b.[Key] AS "data()"
FROM mytable b
WHERE b.RecordID=a.RecordID
ORDER BY b.[Key]
FOR XML PATH('')) AS [Keys]
FROM (SELECT DISTINCT RecordID FROM mytable) a
ORDER BY a.RecordID
____________________________________________________
Deja View - The strange feeling that somewhere, sometime you've optimised this query before
How to get the best help on a forum
http://www.sqlservercentral.com/articles/Best+Practices/61537January 24, 2008 at 5:40 am
Absolutely spot on, exactly what I have been looking for many thanks
January 24, 2008 at 8:05 am
Just an FYI... The original design wasn't bad... 2nd normal form table...
--Jeff Moden
Change is inevitable... Change for the better is not.
January 24, 2008 at 8:16 am
.....Which also might be a necessary "evil" if the table is a "mapping" table (the intermediate table used to create many to many relations). Of course if would then be better if it had its own unique identifier.
----------------------------------------------------------------------------------
Your lack of planning does not constitute an emergency on my part...unless you're my manager...or a director and above...or a really loud-spoken end-user..All right - what was my emergency again?
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply