如何取消透视三种类型的值(包括列标题)



我拥有的数据如下所示:

╔═════════╦═════════╦═════════╦══════════════╦══════════════╦══════════════╗
║ option1 ║ option2 ║ option3 ║ percent_opt1 ║ percent_opt2 ║ percent_opt3 ║
╠═════════╬═════════╬═════════╬══════════════╬══════════════╬══════════════╣
║ 10      ║ 4       ║ 1       ║ 0.67         ║ 0.27         ║ 0.07         ║
╚═════════╩═════════╩═════════╩══════════════╩══════════════╩══════════════╝

因此,如果我想使前三列标题成为行值,那么其他标题也作为更多的行值,我将如何做到这一点?

这就是我的意思:

╔═════════╦════════╦═════════════╗
║ options ║ values ║ percentages ║
╠═════════╬════════╬═════════════╣
║ option1 ║ 10     ║ 0.67        ║
╠═════════╬════════╬═════════════╣
║ option2 ║ 4      ║ 0.27        ║
╠═════════╬════════╬═════════════╣
║ option3 ║ 1      ║ 0.07        ║
╚═════════╩════════╩═════════════╝

这是我正在使用的代码:

declare @tbl as table (
option1 numeric(18,0),
option2 numeric(18,0),
option3 numeric(18,0),
per_opt1 numeric(18,2),
per_opt2 numeric(18,2),
per_opt3 numeric(18,2)
)
insert into @tbl
values (10,4,1,0.67,0.27,0.07)
;
select * from
(
select t.[option1],t.[option2],t.[option3]
from @tbl as t
) as srctbl
unpivot (
val for options in (option1,option2,option3)
) as unpiv

我不知道如何让最后三个百分比列值成为行值,部分原因是我不能有不同的数据类型,而且我不确定如何做。

有什么建议吗?

使用apply

select v.*
from @tbl t cross apply
(values ('option1', option1, percent_opt1),
('option2', option2, percent_opt2),
('option3', option3, percent_opt3)
) v(option, value, percent_opt);

注意:values是一个SQL关键字,所以我更改了中间列的名称。

在我看来,没有任何理由学习unpivot. 它是定制的功能 - 少数数据库中的扩展 - 以"正常"的方式只做一件事。

另一方面,apply支持横向联接,这是标准的(即使语法因数据库而异(。 它们非常强大,取消枢轴是开始了解它们的好方法。

使用横向连接 - 在 SQL Server 中,这称为apply

select x.*
from @tbl t
cross apply (values
('option1', t.option1, t.per_opt1),
('option2', t.option2, t.per_opt2),
('option3', t.option3, t.per_opt3)
) as x(options, vals, percentages)

DB小提琴上的演示

选项 | 价值 | 百分比 :------ |---: |----------: 选项1 |  10 |       0.67 选项2 |   4 |       0.27 选项3 |   1 |       0.07

请注意,values是一个 SQL 关键字 - 我将列重命名为在结果集中vals

最新更新