1

我正在尝试编写一个查询以显示到数据控件。

我在尝试获取我需要的查询时遇到了一些问题。

我希望网格显示:

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/>

数据库表:

products 
id, name

dealers  
id, name

products_to_dealers_xref
product_id, dealer_id, qty

我不知道如何让查询像这样布局。我目前正在尝试 UNION 语句,但仍然无法得到它。

有什么想法或想法吗?

谢谢!

4

1 回答 1

2

您需要使用PIVOT 运算符对查询结果进行透视

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

PS:未测试。

于 2011-10-21T17:44:59.427 回答