Home > Blockchain >  Transforming a sheet into a table with column names as values in SQL Server
Transforming a sheet into a table with column names as values in SQL Server

Time:07-11

I've been given the task of turning the following Excel table into a database table in SQL Server (I have shortened the row count, of course).
Source table

A car has to go to service every 10.000 kilometers, but for some models there is a fast service that applies only to certain mileages (I don't know what mileage is called in kilometers lol).

The table shows car brands and models, and each following column represents the next maintenance service (i.e. column [10] represents the first service, performed at 10.000km, column [20] represents car service performed at 20.000km, etc.).

The values inside the mileage column will indicate if quick service "applies" to the corresponding model and mileage. (i.e. Quick service applies to [Changan A500] at 10.000km and 20.000km, but not at 30.000 or 40.000)
enter image description here

As mentioned before, I need to transform this table into a database table in SQL Server, with the following format.
enter image description here

In this format, there will be a row for every model and the mileage at which quick service corresponds. I hope this clarifies the requirement:
enter image description here

I can make a new SQL table with the source table, and then extract the data and insert it into the required table after transforming it (I assume there is no easy way of putting the information in the new format from the source Excel file).

Right now I'm thinking of using pointers in order to turn this data into a table, but I'm not very good at using pointers and I wanted to know if there might be an easier way before trying the hard way.

The point is to make this scalable, so they can keep adding models and their respective mileages.

How would you do it? Am I complicating myself too much by using pointers or is it a good idea?

Thanks, and sorry I used so many pictures, just thought it might clarify better, and the reason I haven't uploaded any SQL is because I just can't figure out yet how I plan to transform the data.

CodePudding user response:

What you want to do is called unpivot.

You may want to have look here for details how to unpivot the source table with the supported/built-in function …

In Excel (PowerQuery): https://support.microsoft.com/en-us/office/unpivot-columns-power-query-0f7bad4b-9ea1-49c1-9d95-f588221c7098

In SQL Server: https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver16

  • Related