Link to home
Start Free TrialLog in
Avatar of EGormly
EGormlyFlag for United States of America

asked on

Return results ordered by count sort results from a select SQL Query

I have a webapp..

A User clicks on a US State on a map, the State represents a two digit abbreviation of the state they clicked. In the database there are 1000's of locations each one has a two digit state abriviation that indicates what state they are from.  

It is easy to return a list of locations by state
(Select * from Database where State = "Clicked State" Order By Whatever)

What I need is more complicated than that...each location entry has 10 columns  (Product1 to Product10) and if that location has the product in stock, it has a "Y" in that field.

I need to return a list ordered by which location has the most "Y".  So the users would be shown who has the most products in stock.

Database: Stores
Database Table: Locations
Database fields:
Company, Address, State, Zip, Product1, Product2, Product3,  Product4, Product5, Product6, Product7, Product8, Product9, Product10, Product10

How can I do this via a select SQL Statement?
Avatar of Sean Stuber
Sean Stuber

select * from locations
order by
(case when product1='Y' then 1 else 0 end +
case when product2='Y' then 1 else 0 end +
case when product3='Y' then 1 else 0 end +
case when product4='Y' then 1 else 0 end +
case when product5='Y' then 1 else 0 end +
case when product6='Y' then 1 else 0 end +
case when product7='Y' then 1 else 0 end +
case when product8='Y' then 1 else 0 end +
case when product9='Y' then 1 else 0 end +
case when product10 = 'Y' then 1 else 0 end
)

the above sorts from least 'Y' count to most
or, to do sort from most Y to least....

select * from locations
order by
(case when product1='Y' then 1 else 0 end +
case when product2='Y' then 1 else 0 end +
case when product3='Y' then 1 else 0 end +
case when product4='Y' then 1 else 0 end +
case when product5='Y' then 1 else 0 end +
case when product6='Y' then 1 else 0 end +
case when product7='Y' then 1 else 0 end +
case when product8='Y' then 1 else 0 end +
case when product9='Y' then 1 else 0 end +
case when product10 = 'Y' then 1 else 0 end
) desc
ASKER CERTIFIED SOLUTION
Avatar of BrandonGalderisi
BrandonGalderisi
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of EGormly

ASKER

this didn't work for me no matter how I sliced it up.. but I get what it means so that is helpful