Sql 如何将多个列解压为多个列?
我在SybaseASE 15.X数据库中有数据,正在尝试查询整洁的数据。Sybase表中的数据结构如下:Sql 如何将多个列解压为多个列?,sql,sap-ase,Sql,Sap Ase,我在SybaseASE 15.X数据库中有数据,正在尝试查询整洁的数据。Sybase表中的数据结构如下: | Name | Foo_A | Foo_B | Foo_C | Bar_A | Bar_B | Bar_C | -------------------------------------------------------- | abcd | 16 | 32 | 14 | 52 | 41 | 17 | | ... | ... | ... |
| Name | Foo_A | Foo_B | Foo_C | Bar_A | Bar_B | Bar_C |
--------------------------------------------------------
| abcd | 16 | 32 | 14 | 52 | 41 | 17 |
| ... | ... | ... | ... | ... | ... | ... |
我希望以如下方式查询数据:
| Name | Class | FooVal | BarVal |
----------------------------------
| abcd | A | 16 | 52 |
| abcd | B | 32 | 41 |
| abcd | C | 14 | 17 |
| ... | ... | ... | ... |
现在,我已经意识到并正在使用一个联合所有
,但是对于一个看似简单的取消PIVOT
,有什么更简洁、更直接的方法
正如我在这个网站上读到的,MSDN文档、SAP文档和SQL参考资料,UNPIVOT
仅用于两列输出
如果有更多有用的信息,请告诉我。谢谢大家! 使用
UNION ALL
:
select t.*
from (select Name, 'A' as Class, Foo_A as FooVal, Bar_A as BarVal
from table
union all
select Name, 'B', Foo_B, Bar_B
from table
union all
select Name, 'C', Foo_C, Bar_C
from table
) t
order by name;
使用“全部联合”:
select t.*
from (select Name, 'A' as Class, Foo_A as FooVal, Bar_A as BarVal
from table
union all
select Name, 'B', Foo_B, Bar_B
from table
union all
select Name, 'C', Foo_C, Bar_C
from table
) t
order by name;
Sybase(现在的SAP)ASE没有unpivot
功能(您可能已经知道),并且不支持向量函数(可以提供一对多行拆分操作)
除了Yogesh的union all
解决方案外,您可能还需要查看具有3行伪表(假设只有3个类)的交叉联接(笛卡尔积)的性能,例如:
要了解其工作原理,请运行以下命令查看联接生成的结果集,然后应用case
逻辑查看最终行是如何生成的:
select p.Class, m.*
from mytable m,
(select 'A' as Class
union all
select 'B'
union all
select 'C') p
order by m.Name, p.Class
go
Sybase(现在的SAP)ASE没有unpivot
功能(您可能已经知道),并且不支持向量函数(可以提供一对多行拆分操作)
除了Yogesh的union all
解决方案外,您可能还需要查看具有3行伪表(假设只有3个类)的交叉联接(笛卡尔积)的性能,例如:
要了解其工作原理,请运行以下命令查看联接生成的结果集,然后应用case
逻辑查看最终行是如何生成的:
select p.Class, m.*
from mytable m,
(select 'A' as Class
union all
select 'B'
union all
select 'C') p
order by m.Name, p.Class
go