SQL:将汇总表上的 1 列扩展为 3 列

发布于 2024-09-27 06:51:41 字数 463 浏览 0 评论 0原文

我正在编写一个程序来显示产品以及它们所在的商店。

到目前为止,我已经能够编写一个显示数据的 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 技术交流群。

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

发布评论

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

评论(4

云之铃。 2024-10-04 06:51:41
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
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
橘虞初梦 2024-10-04 06:51:41

一个很常见的问题。您需要知道的词是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.

高速公鹿 2024-10-04 06:51:41

现在大多数 RDBM 都支持 Pivot。如果您指定正在使用的数据库,将会有很大帮助。一些示例:MSSQLpostgres(交叉表函数) 等等。

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.

荒芜了季节 2024-10-04 06:51:41

假设您在运行查询之前不知道列名称,此博客
给出了一个很好的解决方案(但要注意注入攻击)。

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).

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