SQL Reformatting table columns

2.4k views Asked by At

I have a table right now which is in a very inconvenient format.
Example:
Columns:

Quarter / ID  / Sales
1     / 234   / 50
1     / 258  / 100 
2     / 234  / 50 
2     / 456  / 125
3     / 258  / 100
3     / 456  / 75 
3     / 555  / 100  
4     / 555  / 50

This is just an example, there are in reality like 5600 columns.

I want to reformat the table so that the example I just showed looks more like:

ID /   Q1   /    Q2    /   Q3    /    Q4
234/   50   /    50    /   0     /     0
258/   100  /    0     /   100   /     0
456/    0   /    125   /   75    /     0
555/    0   /     0    /   100   /     50

Is there a way for me to easily just move these columns, maybe based on some sort of lookup for the ID number? I just need all the data for each ID in one record with separate columns, rather than in 4 records, one for each quarter.

Thanks




---So far all I have done is create a new table with distinct ID. Then I want to use some sort of join or lookup insert that can put all records into Q1 where quarter = 1 and dealer = dealer of record.

2

There are 2 answers

0
Luke K. On BEST ANSWER

Well I figured it out. First I made a new table.

CREATE TABLE newtable (ID varchar (5), Q1 int, Q2 int, Q3 int, Q4 int)

Then I inserted distinct ID's

INSERT INTO newtable
SELECT DISTINCT ID
FROM oldtable

Then for Q1 I made a insert statement as such:

UPDATE newtable
SET newtable.Q1 = oldtable.sales
FROM newtable 
INNER JOIN oldtable
ON newtable.ID = oldtable.ID
WHERE oldtable.quarter = '1'

I then just copied and did it for each quarter, changing to Q2 and then respectively '2' in the WHERE statement.

Just make sure you check for duplicates, my actual dataset had duplicates because I used a select distinct paired with another column.

0
mpriya On

You can use the MySQL CASE statement.

Select id, 
max(case when Quarter=1 then sales else null end) Q1,
max(case when Quarter=2 then sales else null end) Q2,
max(case when Quarter=3 then sales else null end) Q3,
max(case when Quarter=4 then sales else null end) Q4
from your_table_name
group by id;