SQL Reformatting table columns

故事扮演 提交于 2019-12-25 07:35:39

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/18060826/sql-reformatting-table-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!