1

I am trying to write a query to display to a data control.

I'm having some issues trying to get the query I need.

I want the grid to to display:

product name     dealer 1        dealer 2     dealer 3      dealer 4, etc  <br/>
product a        10              12            18           N/A  <br/>
product b        32              N/A           7            4  <br/>
product c        35              36            21           18  <br/>

Database Tables:

products 
id, name

dealers  
id, name

products_to_dealers_xref
product_id, dealer_id, qty

I can't figure out how to get the query to layout like this. I'm currently trying the UNION statement, but still can't get it.

Any thoughts or ideas?

Thanks!

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
kylemac
  • 189
  • 4
  • 19

1 Answers1

2

You need to pivot the results of the query using the PIVOT Operator

select Products.Name,'dealer 1','dealer 2','dealer 3','dealer 4'
from
( select Products.Name,qty from products inner join products_to_dealers_xref pd on Products.id = pd.product_id inner join dealers d on Products.Id = d.id) as p
Pivot 
(sum(qty) for products.name in (['dealer 1'],['dealer 2'],['dealer 3'],['dealer 4'])) as pvt

P. S.: not tested.

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164