簡體   English   中英

切換oracle sql的case語句以決定執行哪個查詢

[英]switch case statement of oracle sql to decide which query to execute

根據列值,我需要在Oracle sql中執行2個不同的查詢。

表A

Col1   Col2
R51    desc_r51
R52    desc_r52
R53    desc_r53

表B

Col1   Type     Username
R51    All      A
R52    Specific B

現在我需要寫一個查詢,

  • 如果表B中的類型為All,則從表A中獲取Col1的所有值
  • 如果類型在表B中是特定的,則獲取與表A和表B的Col1匹配的值

因此,在這種情況下,如果“類型”為“全部”,則結果應為R51,R52,R53

如果“類型”為“特定”,則結果應為R52

有什么幫助嗎?

嘗試這個

select A.col1
  from A
 where exists (select 1 from B where type = 'All')
 union 
select  B.col1
  from A, B
 where A.Col1 = B.Col1 and
       B.Type = 'Specific'

你可以試試看。

SELECT 'SELECT '
       ||CASE
           WHEN TYPE = 'All' THEN (SELECT Listagg(col1, ',')
                                            within GROUP ( ORDER BY col1 )
                                   FROM   tablea)
           WHEN TYPE = 'Specific'
                AND EXISTS (SELECT 1
                            FROM   tablea a
                            WHERE  a.col1 = b.col1) THEN b.col1
         END
       ||' FROM TABLEA;' as select_statement
FROM   tableb b;  

輸出:

SELECT_STATEMENT
SELECT R51,R52,R53 FROM TABLEA;
SELECT R52 FROM TABLEA;

http://sqlfiddle.com/#!4/89872/11/0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM