I have a table with the following sample data:
Name Value
-----------------------
Year 1990
Year 1991
Year 1992
Cash 2000
Cash 4000
Cash 6000
Tax Paid
Tax Unpaid
Tax Pending
Liability 3500
Liability 8500
Liability 9500
I want that data in the following format:
Name Value1 Value2 Value3
-----------------------------------------------------
Year 1990 1991 1992
Cash 2000 4000 6000
Tax Paid Unpaid Pending
Liability 3500 8500 9500
Please note, the number of columns in result table should be dynamic i.e., number of value columns = number of records for an item in original table.
In the example, each item has 3 records so there will be 3 value columns in result table.
Please guide.
Update:
I used below query and it returned data in correct format, but still clueless how to identify number of columns in resultant table. In below example fixed 5 columns are there (name, value1, value2, value3, value4).
with cte as
(
select name ci,value,
row_number() over(partition by [name] order by value) as rn
from TABLE
)
select distinct ci as [name],
(select ct.value from cte ct where ct.ci=cte.ci and ct.rn=1) value1,
(select ct.value from cte ct where ct.ci=cte.ci and ct.rn=2) value2,
(select ct.value from cte ct where ct.ci=cte.ci and ct.rn=3) value3,
(select ct.value from cte ct where ct.ci=cte.ci and ct.rn=4) value4
from cte