我有以下表格:
TABLE1
------
id name
1 n1
2 n2
TABLE2
------
id tipo valor
1 t1 v1
1 t2 v2
2 t1 v1
2 t2 v5
2 t3 v3
我正在努力:
id name t1 t2 t3
1 n1 v1 v2 -
2 n2 v1 v5 v3
有可能吗?我一直在寻找示例,但仍然没有弄清楚.
Is it possible? I have been looking examples but still I don't get nothing clear.
谢谢!
一种选择是使用 PIVOT Clause
One option would be using PIVOT Clause
SELECT *
FROM (SELECT t1.*, t2.tipo, t2.valor
FROM table1 t1
JOIN table2 t2
ON t2.id = t1.id)
PIVOT
(
MAX(valor) FOR tipo IN ( 't1' AS "t1", 't2' AS "t2", 't3' AS "t3" )
)
但这是静态的,例如.需要更新 tipo 列的不同值.为了使其动态化,您可以创建一个函数
but this is static, eg. needs to be updated as different values for tipo column is added. In order to make it dynamic, you can create a function
CREATE OR REPLACE FUNCTION Get_Pivoted_Cols RETURN SYS_REFCURSOR IS
v_recordset SYS_REFCURSOR;
v_sql VARCHAR2(32767);
v_cols VARCHAR2(32767);
BEGIN
SELECT LISTAGG( ''''||tipo||''' AS "'||tipo||'"' , ',' )
WITHIN GROUP ( ORDER BY tipo )
INTO v_cols
FROM ( SELECT DISTINCT tipo FROM table2 );
v_sql := 'SELECT *
FROM (SELECT t1.*, t2.tipo, t2.valor
FROM table1 t1
JOIN table2 t2
ON t2.id = t1.id)
PIVOT
(
MAX(valor) FOR tipo IN ( '|| v_cols ||' )
)';
OPEN v_recordset FOR v_sql;
RETURN v_recordset;
END;
/
然后使用调用
VAR rc REFCURSOR
EXEC :rc := Get_Pivoted_Cols;
PRINT rc
来自 SQL 开发人员的控制台.
from SQL developer's console.
演示
这篇关于Oracle 将行转为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
获取所有产品、类别和元数据的 SQL 查询 woocommSQL query to get all products, categories and meta data woocommerce/wordpress(获取所有产品、类别和元数据的 SQL 查询 woocommerce/wordpre
我可以在不编写 SQL 查询的情况下找出数据库列表Can I figure out a list of databases and the space used by SQL Server instances without writing SQL queries?(我可以在不编写 SQL 查询的情况下
如何创建对 SQL Server 实例的登录?How to create a login to a SQL Server instance?(如何创建对 SQL Server 实例的登录?)
如何通过注册表搜索知道SQL Server的版本和版本How to know the version and edition of SQL Server through registry search(如何通过注册表搜索知道SQL Server的版本和版本)
为什么会出现“数据类型转换错误"?使用 ExWhy do I get a quot;data type conversion errorquot; with ExecuteNonQuery()?(为什么会出现“数据类型转换错误?使用 ExecuteNonQuery()?)
如何将 DataGridView 中的图像显示到 PictureBox?How to show an image from a DataGridView to a PictureBox?(如何将 DataGridView 中的图像显示到 PictureBox?)