views:

38

answers:

4

I'm writing a program that displays products and the stores at which they can be located.

So far, I've been able to write an SQL query that displays data as follows:

Product    Availability
Milk       Store1
Candy      Store1
Eggs       Store1
Milk       Store2
Eggs       Store2
Candy      Store3
Eggs       Store3

Is there any SQL query I can use to have the products grouped on the Product column and the stores at which they can be located expanded into 3 columns as illustrated below?

Product  Store1  Store2  Store3
Milk     Yes     Yes     No
Candy    Yes     No      Yes
Eggs     Yes     Yes     Yes
+3  A: 

A very common question. The word you need to know is pivot. Search StackOverflow for "pivot", or maybe "cross tab" to find a lot of discussions and examples.

Philip Kelley
+4  A: 
SELECT 
    Product,
    MAX(CASE WHEN Availability='Store1' THEN 'Yes' ELSE 'No' END) AS Store1,
    MAX(CASE WHEN Availability='Store2' THEN 'Yes' ELSE 'No' END) AS Store2,
    MAX(CASE WHEN Availability='Store3' THEN 'Yes' ELSE 'No' END) AS Store3
FROM YourTable
GROUP BY Product
Martin Smith
A good solution, but limited by the number of stores in this example. If new store comes up, the query will need update. @Martin: can't we make it dynamic?
Kangkan
@Kangkan - Depends on DBMS. Access has a `transform` operator. SQL Server would require the whole query string to be generated dynamically.
Martin Smith
Thanks, Martin. Since the database is in Access, I used `IIf` instead of `CASE WHEN` and it worked.
Alex Essilfie
@Alex - If you have the need to generate the columns dynamically when you add new stores then check out the [Transform Statement](http://office.microsoft.com/en-us/access-help/transform-statement-HP001032277.aspx) in Access.
Martin Smith
@Kangkan - The number of stores are not going to change, EVER so this query is adequate. Just so I may know, Is there any other query which would do this dynamically [as in for any number of stores]?
Alex Essilfie
if it is Access you can create a PIVOT query and get the results in the correct format
Leslie
+1  A: 

Presuming that you don't know the column names before running the query, this blog gives a good solution (but watch out for injection attacks).

smirkingman
+3  A: 

Most RDBMs support pivot nowadays. It would help a lot if you specified which database you're using. Some examples: MSSQL, postgres (the crosstab function) and so on.

Donnie
Copy and paste fail. Thanks.
Donnie