I have an SQL table like this:
Animal1 Animal2 Corelation
---------+---------------+--------------
Cat Cat 1
Cat Dog 0.6
Cat Mouse 0.8
Dog Cat 0.6
Dog Dog 1
Dog Mouse 0.4
Mouse Cat 0.8
Mouse Dog 0.4
Mouse Mouse 1
I'm looking for an SQL query to return the following results:
Animal 1 Cat Dog Mouse
---------+---------------+------------------+---------------+
Cat 1 0.6 0.8
Dog 6 1 0.4
Mouse 0.8 0.4 1
Basically i want more readable version of the table.
I tried to use pivot like this:
use SymbolsDB
select * from [AnimalsTable]
pivot (
[Corelation]
for [Animal2] in (select * from [Animal2]
)
But it is not working. i am not sure if I understand how the pivot works and if it can be used in my case. Or is there another way to do it? (I am trying to avoid loops because I have 1 million record)
Thanks
In a pivot, the column names must be constant.
So to do this, you need to use dynamic SQL.
You cannot place a
SELECT
statement inside of thePIVOT
to return the list of values, then must be constant. If you are looking for a dynamicPIVOT
then you will need to use something like this:See SQL Fiddle with demo