I need to make a query using pivot or crosstab with columns variables. Is possible? I have the following table:
Data_Id ! Description_Column | Value
--------+--------------------+-------
1 ! Column1 ! value1
1 ! Column2 ! value2
1 ! Column3 ! value3
1 ! Column4 ! value4
2 ! Column1 ! value5
2 ! Column2 ! value6
2 ! Column3 ! value7
2 ! Column4 ! value8
I will need get
Data_Id ! Column1 ! Column2 ! Column3 ! Column4
1 ! value1 ! value2 ! value3 ! value4
2 ! value5 ! value6 ! value7 ! value8
But sometimes i will have:
Data_Id ! Description_Column | Value
--------+--------------------+-------
3 ! Column1 ! value1
3 ! Column2 ! value2
4 ! Column1 ! value5
4 ! Column2 ! value6
I will need get
Data_Id ! Column1 ! Column2
3 ! value1 ! value2
4 ! value5 ! value6
Obs. The rows that I'll need will be selected through a Join. So I will have the number of variable columns.
Thanks for help.
Dynamic Pivotyou'll find many answers; code that writes SQL. (For x columns you need different SQL than for y columns. So you need code that writes SQL for the number of appropriate columns.) In the majority of cases you should keep you data in the original normalised form. You may pivot it in a user interface or other processing layer, but I would recommend against doing so in SQL. [stackoverflow.com/questions/8833679/…