ORACLE SQL-如何在表中的COLUMN_NAME之间进行搜索并获取价值

时间:2019-05-14 06:53:20

标签: sql oracle oracle11g

我有一个Calendarweeks的桌子。我想要2 column_name之间的值。我为column_name使用2下拉菜单。我已经尝试过(见下文),但是不幸的是没有成功。有人可以帮我吗?谢谢

SELECT LISTAGG(COLUMN_NAME, ', ') WITHIN GROUP (ORDER BY COLUMN_ID) 
  FROM ALL_TAB_COLUMNS 
 WHERE TABLE_NAME = 'ALSI_TEST_DELETE' 
   AND COLUMN_NAME BETWEEN :dropdown1 AND :dropdown2

>>>Results:  01, 02, 03, 04 (But without Values, only COLUMN_NAME. I want Values and COLUMN_NAME)

enter image description here

2 个答案:

答案 0 :(得分:0)

似乎您想要这样的查询:

select listagg(column_name,', ') within group (order by column_id)
    as "My Columns List" 
  from user_tab_columns
 where table_name = 'ALSI_TEST_DELETE'
   and column_id between ( select column_id 
                             from user_tab_columns 
                            where table_name = 'ALSI_TEST_DELETE' 
                              and column_name = 'COL1' )
                     and ( select column_id 
                             from user_tab_columns 
                            where table_name = 'ALSI_TEST_DELETE' 
                              and column_name = 'COL4' );

Demo

更优雅的方式:

with utc as
(
 select table_name as tab_name,
        max(case when column_name = 'COL1' then column_id end) as col1,
        max(case when column_name = 'COL4' then column_id end) as col2 
   from user_tab_columns 
  where table_name = 'ALSI_TEST_DELETE'
  group by table_name
)
select listagg(column_name,', ') within group (order by column_id)
    as "My Columns List" 
  from user_tab_columns
  cross join utc
 where table_name = utc.tab_name
   and column_id between utc.col1 and utc.col2;

答案 1 :(得分:0)

我认为您需要UNPIVOT解决问题:

WITH ALSI_TEST_DELETE AS (SELECT 7 "01", 8 "02", 9 "03", 10 "04", 11 "05", 12 "06", 1 ID FROM dual)
SELECT ID, COLUMN_ID, COLUMN_VALUE
  FROM ALSI_TEST_DELETE
UNPIVOT 
 (COLUMN_VALUE
  FOR COLUMN_ID IN ("01","02","03","04","05","06"))
 WHERE COLUMN_ID BETWEEN '01' AND '04'

此查询可能为您提供了一个起点,并且您最终可能会遇到类似以下内容的事情:

SELECT ID, LISTAGG(column_id||': '||column_value,', ') within GROUP (ORDER BY column_id)
  FROM ALSI_TEST_DELETE
UNPIVOT 
 (COLUMN_VALUE
  FOR COLUMN_ID IN ("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53"))
 WHERE COLUMN_ID BETWEEN :dropdown1 AND :dropdown2
 GROUP BY ID