I am trying to pivot some data in SQL, but in all honesty, I dont really understand it. So the data is like this:
Create table Company_rank (company_name varchar(100), Public_rank varchar(20), Peer_rank varchar(20), Online_rank varchar(20), Company_id integer)
Insert into Company_rank (company_name , Public_rank , Peer_rank , Online_rank , Company_id )
VALUES ('ABCCompany', '20','35', '15',1)
VALUES ('BCDCompany', '25','32', '20',2)
VALUES ('DEFCompany', '18','20', '25',3)
What I need to see is the ranking as rows, which I can use to join to another table, for each company. I need the company_id to stay as a column, as I need that for joining, but I dont think that's possible? So, basically, I need the type of ranking and the company_name to be available for joining, as another table has ranking_name, and company_id
Sorry if this seems jumbled!
I was thinking of this:
Rank_type | ABCCompany | BCDCompany | DEF Company |
---|---|---|---|
Public_rank | 20 | 25 | 18 |
Peer_rank | 35 | 32 | 20 |
Online_rank | 15 | 20 | 25 |
But then I've lost the ability to get a key from another table, which needs both the rank_type, and the company_id (this can be derived from company_name or company_id)
So ideally the end result, I would have three tables, which would look like this (company_rank is my staged data, which I am trying to get into these):
Tables | Expected values | Notes |
---|---|---|
rank_history | ||
Rank_History_Id | 1 | Identity |
Ranking_Id | 1 | FK to_Ranking_type |
Value | 15 | |
Valid_from | 04/11/2022 | |
Valid_to | 99/99/9999 |
Ranking_type | ||
---|---|---|
Ranking_Id | 1 | Identity |
name | Online_rank | |
Company_id | 1 | FK to Company |
Create table Company | ||
---|---|---|
Company_id | 1 | Identity |
Company_name | ABCCompany' |