Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load data from denormalized file into a normalized table

I receive a denormalized text file that must be loaded into a normalized table.

Denormalized table:

CustomerID -- Category -- Category2 -- Category3 -- Category4
1 -- A -- B -- C -- D

When this is normalized, it should look like:

CustomerID -- Category
1 -- A
1 -- B
1 -- C
1 -- D

What is the best way to write a T-SQL statement to achieve this (SQL Server 2008)?

like image 467
Sesame Avatar asked Aug 09 '10 17:08

Sesame


People also ask

What can normalization achieve for a denormalized table?

Normalization increases the number of tables and joins. In contrast, denormalization reduces the number of tables and join. Disk space is wasted in denormalization because same data is stored in different places. On the contrary, disk space is optimized in a normalized table.

What happens when you store the data in a denormalized way in Rdbms?

Denormalization is the process of adding precomputed redundant data to an otherwise normalized relational database to improve read performance of the database. Normalizing a database involves removing redundancy so only a single copy exists of each piece of information.

What is the main disadvantage of data denormalization in Nosql database?

Denormalization has these disadvantages: Denormalization usually speeds retrieval but can slow updates. This is not a real concern in a DSS environment. Denormalization is always application-specific and needs to be re-evaluated if the application changes.

Which technique can you use to Denormalize data?

Using pre-joined tables This denormalization technique can be used when you have to make lots of queries against many different tables – and as long as stale data is acceptable.


1 Answers

Use the UNPIVOT keyword: http://technet.microsoft.com/en-us/library/ms177410.aspx

Naturally you'll want to replace [File] with some sort of OpenRowSet query or use the import/export wizard to get the data into a temp table.

SELECT CustomerId, Category
FROM 
(
   SELECT CustomerId, Category, Category2, Category3, Category4
   FROM [File]

) tblDenormalized
UNPIVOT
(
   Category FOR Column IN 
   (Category, Category2, Category3, Category4)
) AS unpivot;
like image 70
Shlomo Avatar answered Sep 23 '22 22:09

Shlomo