首页 > 解决方案 > 如何在查询返回中设置行号等于列名?

问题描述

我正在使用 SQL Server 2019 中的数据库内 Python 引擎计算大型表中列之间的相关性,并且由于此计算返回对角矩阵,因此希望能够在 SSMS 中查看结果,其中标记为镜像列的行名字。

我知道 SQL 查询的基础知识,但了解的不多,所以也许我没有准确地表达我的搜索。

这是我的代码示例:

execute sp_execute_external_script 
@language = N'Python',
@script = N'
import pandas as pd
from pandas import DataFrame

df = InputDataSet.corr()
OutputDataSet = df

',
@input_data_1 = N'select GHI ,
MNO,
JKL
from PIVOTED_TIME_ID_MATRIX'

with result sets ((GHI float,
MNO float,
JKL float))

这将返回:

***** GHI | MNO | JKL
Row 1   1   0.5   0.5
Row 2 0.5     1   0.5
Row 3 0.5   0.5     1 

我想看看:

***** GHI | MNO | JKL
GHI     1   0.5   0.5
MNO   0.5     1   0.5
JKL   0.5   0.5     1 

这可能吗?

标签: pythonsqlsql-serverpandassql-server-2019

解决方案


我最终结合了上面的建议来使用 df.columns,以及一种从这里重新排列列的方法,以及一种解决方法来产生我正在寻找的输出。

...'
df = InputDataSet.corr()
#puts the names of the existing columns into a new column on the end of df
df["columns"] = df.columns 
cols = df.columns.tolist()
#shift the "columns" column to the front of the dataframe
cols = cols[-1:] + cols[:-1]
df = df[cols]
OutputDataSet = df

',
@input_data_1 = N'select GHI ,
MNO,
JKL
from PIVOTED_TIME_ID_MATRIX'

with result sets ((column_names varchar(max), --add a new column in the result set
GHI float,
MNO float,
JKL float))

推荐阅读