简体   繁体   English

动态透视表数据 | mySQL

[英]Dynamically Pivoting Table Data | mySQL

Essentially I have a table in my database called Table1 with the following data:本质上,我的数据库中有一个名为Table1的表,其中包含以下数据:

在此处输入图像描述

The table has a ProductID that repeats because the values of AssignedColour , ColourFinding and ColourPower vary.该表有一个重复的 ProductID,因为AssignedColourColourFindingColourPower的值不同。

I would like to present all ProductID data in one single row, meaning if there is more than one AssignedColour , ColourFinding and ColourPower listed, it will contain a number at the end.我想在一行中显示所有ProductID数据,这意味着如果列出了多个AssignedColourColourFindingColourPower ,它将在末尾包含一个数字。

The final result I of the SELECT query should look like the following: SELECT 查询的最终结果 I 应如下所示:

在此处输入图像描述

The number of columns presented horizontally is based on the number of AssignedColour per ProductID水平显示的列数基于每个ProductIDAssignedColour

Is something like this possible to accomplish in a mySQL SELECT Query?这样的事情是否可以在 mySQL SELECT 查询中完成?

An SQL query cannot expand the number of columns of the result set depending on the data values it discovers during query execution. SQL 查询无法根据查询执行期间发现的数据值扩展结果集的列数。 The columns in the SELECT-list must be fixed at the time the query is prepared, before it reads any data. SELECT-list 中的列必须在准备查询时固定,然后再读取任何数据。

Also the column names cannot be changed during the query execution.此外,在查询执行期间不能更改列名。 They must be set at the time the query is prepared.它们必须在准备查询时设置。

There's no way to do what you are describing in a single SQL query.没有办法做你在单个 SQL 查询中描述的内容。 Your options are:您的选择是:

  • Do two queries: one to enumerate the colors per product, and then use the result of the first to format a second query with the columns you want.执行两个查询:一个枚举每个产品的 colors,然后使用第一个查询的结果来格式化第二个查询,其中包含您想要的列。
  • Do one query to fetch the data in rows as it exists in your table, then write code in your app to display it in rows however you think is best.执行一个查询以获取表中存在的行中的数据,然后在您的应用程序中编写代码以按您认为最好的方式将其显示在行中。

Either way, you have to write at least a bit of code in the client.无论哪种方式,您都必须在客户端中编写至少一点代码。 You can't do this in one query.您不能在一个查询中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM