简体   繁体   中英

ORACLE SQL-How can i search between COLUMN_NAME in a Table and get value

I have a table with Calendarweeks . I want the values ​​of between 2 column_name . I use 2 dropdown for column_name . I have already tried (see below) but unfortunately not success. Could anyone help me, please? Thank you

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)

在此处输入图片说明

Seems You want such a query as below :

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

More elegant way to be considered :

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;

I think you need UNPIVOT for your problem:

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'

This query might give you a start and you might end up with something like the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM