-1

We are doing a date migration and I'd like to extract the data from the old system in one clean MySQL query so that we can run it before configurations and again right before go live.

I'm limited to the types of commands I can use in MySQL to mostly SELECT commands as I only have read access to the database.

AND the new vendor needs contact data for suppliers in a certain format and it looks like I don't have much of a choice in the matter.

With that all said, is this possible in MySQL...

Given a table of suppliers, that contains a joined table of contacts where the output lists the contacts down in rows grouped by supplier, can I transpose just the contact grouping into columns to the right dynamically.

I don't know how many contacts there will be for each supplier, could be none, one or 20. So I'd like it to be dynamic if that is possible.

It's hard to explain so please see image below. I tried to type this into the body but it didn't look right. This image should explain better what I need to do.

Image in case the output above wraps wrong

I don't really have code to share on this. As I'm not sure where to start. I've seen questions about creating a pivot table but it is sort of what want and sort of not. And I am not sure I can actually use those commands.

I'm looking for the guidance on how to write this, so I can apply to my current query, which outputs similarly to the current output above.

Well, I haven't tried a lot. I've been researching pivot tables in MySQL and how to create one, but get stuck when trying to apply the concept because it's not really a pivot table, I'm more transposing than pivoting. I'm not summing any data up or making any calculations. I just need to list the contacts horizontally in one row instead of vertically.

Like I said above. The number of contacts varies greatly so it would be hard to create a set number of contacts.

Where do I start and what concepts should I be using.

drun2969
  • 11
  • 2
  • Please post code, data, and results as text, not screenshots ([how to format code in posts](https://stackoverflow.com/help/formatting)). [Why should I not upload images of code/data/errors?](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors) http://idownvotedbecau.se/imageofcode – Barmar Sep 01 '23 at 19:58
  • You are going the wrong direction here. Your original database schema is the RIGHT way to store contacts. Your new schema is the WRONG way. What happens if someone has 4 contacts? Think of how complicated it becomes to find a particular email address. Leave it the way it is. – Tim Roberts Sep 01 '23 at 19:59
  • *yeah I just realised that too Barmar – easleyfixed Sep 01 '23 at 20:00
  • Are you using MySQL 8.0? If so, you can do a pivot using `ROW_NUMBER()` within each group to get the numeric suffix of the column number. – Barmar Sep 01 '23 at 20:02

0 Answers0