SQL中的数据透视表,但将度量名称保留在列中

问题描述

我无法正确地摆放桌子。

我的输入是原始数据表:

file1 = open('myfile.txt','r') 
Lines = file1.readlines() 

count = 0
lineNumStart,lineNumEnd = 1,7
outStringJoined = ""
for line in Lines: 
    if count>=lineNumStart and count<lineNumEnd:
        outStringJoined += line.strip()
    else:
        outStringJoined += line
    count+=1
print(outStringJoined)

我想把年数排成一行,但我也想保持录入和退学的度量作为行名。例如,我想要一个这样的表:

+------+---------+------------+----------+
| YEAR | FACULTY | ADMISSIONS | DROPOUTS |
+------+---------+------------+----------+
| 2018 | LAW     |         15 |        2 |
| 2019 | LAW     |         18 |        4 |
| 2020 | LAW     |         11 |        1 |
| 2018 | MATH    |         19 |        1 |
| 2019 | MATH    |         17 |        6 |
| 2020 | MATH    |         24 |        5 |
+------+---------+------------+----------+

我可以使用:

+---------+------------+------+------+------+
| FACULTY |  MEASURE   | 2018 | 2019 | 2020 |
+---------+------------+------+------+------+
| LAW     | ADMISSIONS |   15 |   18 |   11 |
| LAW     | DROPOUTS   |    2 |    4 |    1 |
| MATH    | ADMISSIONS |   19 |   17 |   24 |
| MATH    | DROPOUTS   |    1 |    6 |    5 |
+---------+------------+------+------+------+

但是我需要同时调整两个度量,并且仍然获得度量名称列。有什么想法吗?

解决方法

那是不可旋转的,然后旋转。如果您的数据库支持横向联接和values(),则可以执行以下操作:

select
    t.faculty,x.measure,sum(case when t.year = 2018 then x.value end) value_2018,sum(case when t.year = 2019 then x.value end) value_2019,sum(case when t.year = 2020 then x.value end) value_2020
from mytable t
cross apply (values ('admission',admission),('dropout',dropout)) as x(measure,value)
group by t.faculty,x.measure
,

我将取消使用apply(假设您正在使用SQL Server)并重新聚合:

select t.faculty,v.measure,max(case when year = 2018 then val end) as [2018],max(case when year = 2019 then val end) as [2019],max(case when year = 2020 then val end) as [2020]
from t cross apply
     (values ('ADMISSIONS',ADMISSIONS),('DROPOUTS',DROPOUTS)
     ) v(measure,val)
group by t.faculty,v.measure