SQL Server取消透视两列 [英] SQL Server unpivot two columns

查看:63
本文介绍了SQL Server取消透视两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图将一个数据表透视以获取3列

I'm trying to pivot a table to get 3 columns

我的示例表如下:

CREATE TABLE tbl1 (A1 int, cA1 int,A2 int, cA2 int,A3 int, cA3 int)
GO
INSERT INTO tbl1  VALUES (60,2,30,3,10,5);
GO

我正在使用下面的查询从两列中获取结果:

I am using the query below to get tthe results from two columns:

select A, value from tbl1
unpivot
(
value
for A in ([A1], [A2],[A3])
) un1;

结果类似于:

A | value
--+-------
A1|60
A2|30
A3|10

但是我想添加和第二列,结果应为:

but I want to add and second column with and the results to be like :

A | value1 | value2
--+--------+--------
A1| 60     | 2
A2| 30     | 3
A3| 10     | 5

有帮助吗?

推荐答案

我会使用APPLY:

select v.*
from tbl1 t cross apply
     (values ('A1', t.A1, t.cA1),
             ('A2', t.A2, t.cA2),
             ('A3', t.A3, t.cA3)
     ) v(A, value1, value2);

CROSS APPLY实现了 lateral 连接.尽管取消数据是开始学习横向联接的一种简单方法,但它比仅取消数据更强大.

CROSS APPLY implements a lateral join. This is much more powerful than merely unpivoting data, although unpivoting data is one simple way to start learning about lateral joins.

这篇关于SQL Server取消透视两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆