简体   繁体   中英

Dynamically Pivoting Table Data | mySQL

Essentially I have a table in my database called Table1 with the following data:

在此处输入图像描述

The table has a ProductID that repeats because the values of AssignedColour , ColourFinding and ColourPower vary.

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.

The final result I of the SELECT query should look like the following:

在此处输入图像描述

The number of columns presented horizontally is based on the number of AssignedColour per ProductID

Is something like this possible to accomplish in a mySQL SELECT Query?

An SQL query cannot expand the number of columns of the result set depending on the data values it discovers during query execution. The columns in the SELECT-list must be fixed at the time the query is prepared, before it reads any data.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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