我的问题是,有一些背景:
我必须基于表元数据(列格式)生成一些sql查询,其结果类似于:
TABLENAME1|COL1 TABLENAME1|COL2 TABLENAME2|COL1 TABLENAME2|COL2 TABLENAME2|COL3 TABLENAME3|COL1 TABLENAME4|COL1 TABLENAME4|COL2 ... /*some other 1800 rows */
(是的,它是有序的。)我需要的是基于第一列来转置此数据,因此预期的输出将是:
TABLENAME1|COL1|COL2|NULL TABLENAME2|COL1|COL2|COL3 TABLENAME3|COL1|NULL|NULL TABLENAME4|COL1|COL2|NULL /* less then 1800 rows ;-) */
是否可以使用Oracle SQL?
提前致谢!
如果要为每个调用生成查询或使用硬编码的max-column-count,则可以执行以下操作:
WITH tab AS ( SELECT table_name, column_name FROM user_tab_cols WHERE column_id <= 4 ) -- user_tab_cols used to provide test data, use your table instead SELECT MAX(c1) c1, MAX(c2) c2, MAX(c3) c3, MAX(c4) c4 FROM (SELECT table_name, DECODE( column_id, 1, column_name ) c1, DECODE( column_id, 2, column_name ) c2, DECODE( column_id, 3, column_name ) c3, DECODE( column_id, 4, column_name ) c4 FROM ( SELECT table_name, column_name, ROW_NUMBER() OVER ( PARTITION BY table_name ORDER BY column_name ) column_id FROM tab ) ) GROUP BY table_name ORDER BY table_name
如果足够以这种形式获得它
TABLENAME1|COL1,COL2 TABLENAME2|COL1,COL2,COL3