从多个表到网格的 SQL 查询

发布于 2024-12-11 06:38:23 字数 664 浏览 0 评论 0原文

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

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

我希望网格显示:

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 语句,但仍然无法得到它。

有什么想法或想法吗?

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寄与心 2024-12-18 06:38:23

您需要使用 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:未经测试。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文