Please start any new threads on our new site at http://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | 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
 Sql Query
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

goodman2253
Yak Posting Veteran

88 Posts

Posted - 07/09/2013 :  10:30:39  Show Profile  Reply with Quote
Hello All

I am struck in a query and want some help. I have a table name table1 which contain two coulumn columnA and columnB as below

columnA------columnB
12------A
12------B
13------A
14------C
15------B
13------B
16------A
15------C
16------B

I want to write the sql query which give output as below

Output Required

ColumnA------Count------Common
12------2------A,B
13------2------A,B
14------1------C
15------2------B,C
16------2------A,B

SwePeso
Patron Saint of Lost Yaks

Sweden
30421 Posts

Posted - 07/09/2013 :  10:49:40  Show Profile  Visit SwePeso's Homepage  Reply with Quote
-- Prepare sample data
DECLARE	@Sample TABLE
	(
		ColumnA TINYINT NOT NULL,
		ColumnB CHAR(1) NOT NULL
	);

INSERT	@Sample
	(
		ColumnA,
		ColumnB
	)
VALUES	(12, 'A'),
	(12, 'B'),
	(13, 'A'),
	(14, 'C'),
	(15, 'B'),
	(13, 'B'),
	(16, 'A'),
	(15, 'C'),
	(16, 'B');

-- SwePeso
SELECT		b.ColumnA,
		b.Items AS [Count],
		STUFF(f.Data, 1, 1, '') AS Common
FROM		(
			SELECT		ColumnA,
					COUNT(*) AS Items
			FROM		@Sample
			GROUP BY	ColumnA
		) AS b
CROSS APPLY	(
			SELECT DISTINCT	',' + x.ColumnB
			FROM		@Sample AS x
			WHERE		x.ColumnA = b.ColumnA
			ORDER BY	',' + x.ColumnB
			FOR XML		PATH('')
		) AS f(Data)
ORDER BY	b.ColumnA



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
  Previous Topic Topic Next 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.05 seconds. Powered By: Snitz Forums 2000