SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Merging several records of a field
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Khus
Starting Member

2 Posts

Posted - 09/08/2013 :  03:27:46  Show Profile  Reply with Quote
Hi
I have a table like
Number Desc
1 Bank
2 Shop
3 Store
2 Home
1 Mall
2 House

I want to have a result as
Number Desc All
1 Bank Mall
2 Shop Home House
3 Store

Can you someone help to do this using a proper select syntax



SwePeso
Patron Saint of Lost Yaks

Sweden
29910 Posts

Posted - 09/08/2013 :  05:08:21  Show Profile  Visit SwePeso's Homepage  Reply with Quote
How do you plan to make sure "Shop" is handled before "Home" which should be handled before" House"?



Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA
Go to Top of Page

Khus
Starting Member

2 Posts

Posted - 09/08/2013 :  06:29:42  Show Profile  Reply with Quote
Thank you for the reply.
I will have a field for the order like
Number Desc Order
1 Bank 1
2 Shop 1
3 Store 1
2 Home 2
1 Mall 2
2 House 3



quote:
Originally posted by SwePeso

How do you plan to make sure "Shop" is handled before "Home" which should be handled before" House"?



Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA

Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

Sweden
29910 Posts

Posted - 09/08/2013 :  13:44:37  Show Profile  Visit SwePeso's Homepage  Reply with Quote
DECLARE	@Sample TABLE
	(
		Number TINYINT NOT NULL,
		[Desc] VARCHAR(100) NOT NULL,
		[Order] TINYINT NOT NULL
	);

INSERT	@Sample
VALUES	(1, 'Bank', 1),
	(2, 'Shop', 1),
	(3, 'Store', 1),
	(2, 'Home', 2),
	(1, 'Mall', 2),
	(2, 'House', 3);

-- SwePeso
SELECT		n.Number,
		STUFF(CAST(f.Data AS VARCHAR(MAX)), 1, 1, '') AS [Desc All]
FROM		(
			SELECT		Number
			FROM		@Sample
			GROUP BY	Number
		) AS n
CROSS APPLY	(
			SELECT		' ' + x.[Desc]
			FROM		@Sample AS x
			WHERE		x.Number = n.Number
			ORDER BY	x.[Order]
			FOR XML		PATH(''),
					TYPE
		) AS f(Data);



Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000