SQL Server Is PIVOT the right command

oxf4rvwz  于 10个月前  发布在  其他
关注(0)|答案(2)|浏览(92)

I have a table imported form a different application the format of the import is

ID1 Variable1   value 
ID1 Variable2   value
ID1 Variable3   value
ID2 Variable1   value 
ID2 Variable2   value
ID2 Variable3   value
ID3 Variable1   value 
ID3 Variable2   value
ID3 Variable3   value

I need to change the format so that it is as below

[ID]    [Variable1] [Variable2] [Variable3]
ID1     value       value       value
ID2     value       value       value
ID3     value       value       value

When I look this up on the internet PIVOT is the option suggested is this the correct approach as I don’t want to aggregate any value.

I have not been able to convert any of the examples that I have seen into code this prompted me to ask Is PIVOT the right command.

bxgwgixi

bxgwgixi1#

Consider:

DECLARE @Table TABLE (ID VARCHAR(3), Variable VARCHAR(10), Value VARCHAR(5));
INSERT INTO @Table (ID, Variable, Value) VALUES
('ID1', 'Variable1', 'value'),  ('ID1', 'Variable2', 'value'), ('ID1', 'Variable3', 'value'), ('ID2', 'Variable1', 'value'),  
('ID2', 'Variable2', 'value'), ('ID2', 'Variable3', 'value'), ('ID3', 'Variable1', 'value'),  ('ID3', 'Variable2', 'value'), 
('ID3', 'Variable3', 'value');

SELECT *
  FROM @Table
  PIVOT (
         MAX(Value) FOR Variable IN (Variable1, Variable2, Variable3)
        ) p;
IDVariable1Variable2Variable3
ID1valuevaluevalue
ID2valuevaluevalue
ID3valuevaluevalue

PIVOT requires an aggregate. Given your values are all [N]VARCHAR it doesn't really matter if we use MIN or MAX. In order to have a column returned from the PIVOT it must be included in the FOR . Adding , Variable4 would include another column with NULL values, as there aren't any in the table. Removing , Variable3 would remove that column, ignoring any values present for it.

erhoui1w

erhoui1w2#

You can do a 3-dimensional join:

SELECT t1.ID, t1.value AS Variable1, t2.value AS Variable2, t3.value AS Variable3
FROM yourtable t1
JOIN yourtable t2
ON t1.ID = t2.ID
JOIN yourtable t3
ON t2.ID = t3.ID
WHERE t1.Variable = 'Variable1' AND
      t2.Variable = 'Variable2' AND
      t3.Variable = 'Variable3'

This way, you join together 3 records for each row, force t1 to be of Variable1, t2 to be of Variable2, t3 to be of Variable3. And you have no aggregation at play. You simply read all the values as they are and name them as Variable1, Variable2 and Variable3 for clarity's sake.

However, the query above assumes that for each ID you have a Variable1, a Variable2 and a Variable3. If you cannot make that assumption, then you will need to use outer joins. But, since your question's example does not suggest this being possible, this answer for the time being will assume that each tuple will have all of the 3 components existent.

相关问题