I have the following query that I get with this query:
Select Año, Tip, Est, t1, t2, t3 From Tabla1
Año Tip Est Zo t1 t2 t3
2003 1 A 6 12 14 17
2003 1 A 7 12 15 18
2003 1 A 8 13 16 19
2003 1 A 9 10 12 14
2003 1 A 10 12 14 17
2004 1 A 1 11 13 15
How can I perform the query to have a result similar to this?
Año Tip Est Zo Ts
2003 1 A 6 12
2003 1 A 6 14
2003 1 A 6 17
2003 1 A 7 12
2003 1 A 7 15
2003 1 A 7 18
2003 1 A 8 13
2003 1 A 8 16
2003 1 A 8 19
2003 1 A 9 10
2003 1 A 9 12
2003 1 A 9 14
What is being done is placing the columns t1, t2, t3 in a row with the same years to which they belong.
How could I achieve that?
SQL Server allows you to do a
UNPIVOT
, designed for just this situation:Another interesting option is to use
CROSS APPLY
:In both cases, performance should be good since you only need to traverse the table once.
Although I think I understand you want to group it in a single column, you can do it with a
union all
You must add
ORDER BY
.Try the following query: