在 SQL Table 内转置数据,不使用 Pivot 选项
Transposing Data Out within SQL Table not using Pivot option
我正在尝试转置 SQL Table 中的数据,但这是一种自定义转置技术,可能会将值串联到一个 table 单元格中。
下面是一个示例数据集。来自 [master].[dbo].[OLE DB Destination 3]
_ParentKey Field |name |type
1 |CHEVRON MIDCONTINENT LP |Grantor
1 |CHEVRON USA INC |Grantor
1 |UNION OIL CO |Grantor
1 |XBM PRODUCTION LP |Grantor
1 |CASILLAS PETROLEUM |Grantee
2 |OSAGE OIL AND GAS PROPERTIES |Grantor
2 |CASILLAS PETROLEUM |Grantee
下面是查询的期望输出
_ParentKey Field |Grantor |Grantee
1 |CHEVRON MIDCONTINENT LP, CHEVRON USA INC, UNION OIL, XBM PRODUCTION LP|CASILLAS PETROLEUM
2 |OSAGE OIL AND GAS PROPERTIES |CASILLAS PETROLEUM
我假设 _ParentKey Field
字段将是 "primary key" 以转置此数据。 "name" 列中的每个名称都将具有 Grantor 或 Grantee Type。
免责声明:我只知道基本的 SQL 直到连接、子查询和一些数据操作。
我会推荐条件聚合和字符串聚合函数string_agg()
:
select
_ParentKey,
string_agg(case when type = 'Grantor' then name end, ', ') grantor,
string_agg(case when type = 'Grantee' then name end, ', ') grantee
from mytable
group by _ParentKey
我正在尝试转置 SQL Table 中的数据,但这是一种自定义转置技术,可能会将值串联到一个 table 单元格中。
下面是一个示例数据集。来自 [master].[dbo].[OLE DB Destination 3]
_ParentKey Field |name |type
1 |CHEVRON MIDCONTINENT LP |Grantor
1 |CHEVRON USA INC |Grantor
1 |UNION OIL CO |Grantor
1 |XBM PRODUCTION LP |Grantor
1 |CASILLAS PETROLEUM |Grantee
2 |OSAGE OIL AND GAS PROPERTIES |Grantor
2 |CASILLAS PETROLEUM |Grantee
下面是查询的期望输出
_ParentKey Field |Grantor |Grantee
1 |CHEVRON MIDCONTINENT LP, CHEVRON USA INC, UNION OIL, XBM PRODUCTION LP|CASILLAS PETROLEUM
2 |OSAGE OIL AND GAS PROPERTIES |CASILLAS PETROLEUM
我假设 _ParentKey Field
字段将是 "primary key" 以转置此数据。 "name" 列中的每个名称都将具有 Grantor 或 Grantee Type。
免责声明:我只知道基本的 SQL 直到连接、子查询和一些数据操作。
我会推荐条件聚合和字符串聚合函数string_agg()
:
select
_ParentKey,
string_agg(case when type = 'Grantor' then name end, ', ') grantor,
string_agg(case when type = 'Grantee' then name end, ', ') grantee
from mytable
group by _ParentKey