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.
2条答案
按热度按时间bxgwgixi1#
Consider:
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 thePIVOT
it must be included in theFOR
. Adding, Variable4
would include another column withNULL
values, as there aren't any in the table. Removing, Variable3
would remove that column, ignoring any values present for it.erhoui1w2#
You can do a 3-dimensional join:
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.