简体   繁体   中英

Transpose data with MS Access SQL

I have a dataset returned from a MS Access SQL query that looks like Table 1.

Table 1

Year    Quarter P1  P2
2013    Q1      1   6
2013    Q2      2   9
2013    Q3      5   1
2013    Q4      6   4
2014    Q1      4   3
2014    Q2      8   2
2014    Q3      6   5
2014    Q4      2   4
2015    Q1      2   3
2015    Q2      1   1

I would like to transpose the data to look like Table 2.

Table 2

Year    Quarter Value   P1
2014    Q3      P1      6
2014    Q3      P2      5
2014    Q4      P1      2
2014    Q4      P2      4
2015    Q1      P1      2
2015    Q1      P2      3
2015    Q2      P1      1
2015    Q2      P2      1

I've been looking around internet and understand that I need to use TRANSPOSE in the query but I can't figure out how to use it especially since I don't want to transpose the two first columns.

I think you can do what you want with union all :

select year, quarter, 'P1' as value, p1
from table1
union all
select year, quarter, 'P2' as value, p2
from table1;

You might want to add where clauses to get only the rows in your desired results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM