Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Values From a table as Column Headers

I have a table 'propertyvalues' as follows:

ID  FileID  Property  Value
1 x Name 1.pdf
2 x Size 12567
3 x Type application/pdf
4 y Name 2.pdf
5 y Size 23576
6 y Type application/pdf
......
and so on

How to write a SQL query on the table above to fetch a result like below

 
FileID  Name     Size      Type
x 1.pdf 12567 application/pdf
y 2.pdf 23576 application/pdf
like image 702
Ankit Khatri Avatar asked Sep 27 '12 10:09

Ankit Khatri


People also ask

How would you select the columns with the headers?

Clicking on the column header in the Results Browser will sort the data by that column. However, if you control-click on the column header (hold down the Ctrl key and click on the header), you can select all the visible (loaded) data in that column in the Results Browser.

How do I select column headers in SQL?

In SQL Server, you can select COLUMN_NAME from INFORMATION_SCHEMA. COLUMNS .


1 Answers

You did not specify RDBMS, if you know the number of columns to transform then you can hard-code the values:

select FileId,
  max(case when property = 'Name' then value end) Name,
  max(case when property = 'Size' then value end) Size,
  max(case when property = 'Type' then value end) Type
from yourtable
group by FileId

This is basically a PIVOT function, some RDBMS will have a PIVOT, if you do then you can use the following, PIVOT is available in SQL Server, Oracle:

select *
from 
(
  select FileId, Property, Value
  from yourTable
) x
pivot
(
  max(value)
  for property in ([Name], [Size], [Type])
) p

If you have an unknown number of columns to transform, then you can use a dynamic PIVOT. This gets the list of columns to transform at run-time:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(property) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ' + @cols + ' from 
             (
                select FileId, Property, Value
                from yourtable
            ) x
            pivot 
            (
                max(value)
                for Property in (' + @cols + ')
            ) p '

execute(@query)
like image 104
Taryn Avatar answered Oct 15 '22 16:10

Taryn