SQL:将汇总表上的 1 列扩展为 3 列
我正在编写一个程序来显示产品以及它们所在的商店。
到目前为止,我已经能够编写一个显示数据的 SQL 查询,如下所示:
Product Availability
Milk Store1
Candy Store1
Eggs Store1
Milk Store2
Eggs Store2
Candy Store3
Eggs Store3
是否有任何 SQL 查询可以用来将产品分组在 Product 列上,并将它们所在的商店扩展为 3 列,如下所示如下图所示?
Product Store1 Store2 Store3
Milk Yes Yes No
Candy Yes No Yes
Eggs Yes Yes Yes
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一个很常见的问题。您需要知道的词是pivot。在 StackOverflow 中搜索“pivot”,或者“cross tab”,可以找到大量讨论和示例。
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.
现在大多数 RDBM 都支持 Pivot。如果您指定正在使用的数据库,将会有很大帮助。一些示例:MSSQL、postgres(交叉表函数) 等等。
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.
假设您在运行查询之前不知道列名称,此博客
给出了一个很好的解决方案(但要注意注入攻击)。
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).