SQL Grouped on column A, column B records with "higest count"

I would like to select items from a table:
- Grouped on column_A
- With the value of column_B that has the highest count of records

e.g.
column_A, column_B
car, red
car, red
car, green
motorbike, yellow
motorbike, blue
motorbike, orange
motorbike, orange

I would want the results
column_A, column_B
car, red
motorbike, orange

Where there are equal highest counts, I'm happy to take either value for column_B
LVL 1
BeamsonAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Let me know if this floats your boat.  Guessing there's a more elegant way to pull this off but this meets your requirements.
CREATE TABLE #foo (column_A VARCHAR(10), column_B VARCHAR(10))

INSERT INTO #foo (column_A, column_B) 
VALUES 
	('car', 'red'), 
	('car', 'red'), 
	('car', 'green'), 
	('motorbike', 'yellow'), 
	('motorbike', 'blue'), 
	('motorbike', 'orange'), 
	('motorbike', 'orange')

;WITH cte AS (
SELECT Column_A, Column_B, COUNT(Column_B) AS the_count
FROM #foo 
GROUP BY Column_A, Column_B), 
cte_grouped AS (
SELECT Column_A, Column_B, 
	RANK() OVER (PARTITION BY Column_A ORDER BY the_count DESC) AS rank_order
FROM cte) 
SELECT Column_A, Column_B FROM cte_grouped WHERE rank_order = 1

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
BeamsonAuthor Commented:
That does it for me!

Thanks Jim
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.