2015-10-15 37 views
1

根據一個sql查詢返回的結果,我必須決定調用哪個SQL查詢。可能嗎?根據另一個查詢返回的條件觸發postgres中的不同查詢

下面是一個演示:

select start, end, max from table. 
If max < 10 
select ob1, ob2, start, end from t1 
if max >=10 and < 50 
select ob1, ob2, start, end from t2 
if max >= 50 
select ob1, ob2, start, end from t2 
+0

最大的整數,開始和結束日期,OB1 ,ob2是整數... – Jayant

回答

2

您可以使用類似有條件的工會

select ob1, ob2, q2."start", q2."end" 
from (
    select "start", "end", "max" 
    from the_table 
    ) q1, 
lateral (
     select ob1, ob2, "start", "end" 
     from t1 
     where "max" < 10 
    union 
     select ob1, ob2, "start", "end" 
     from t2 
     where "max" >=10 and "max" < 50 
    union 
     select ob1, ob2, "start", "end" 
     from t3 
     where "max" >= 50 
    ) q2 

閱讀文檔中關於LATERAL Subqueries

在Postgres的9.2可以使用with查詢:

with m as (
    select "max" 
    from the_table) 
select ob1, ob2, q."start", q."end" 
from (
     select ob1, ob2, "start", "end" 
     from t1, m 
     where "max" < 10 
    union 
     select ob1, ob2, "start", "end" 
     from t2, m 
     where "max" >=10 and "max" < 50 
    union 
     select ob1, ob2, "start", "end" 
     from t3, m 
     where "max" >= 50 
) q 
+0

他y ...橫向關鍵字不適用於postgres 9.2 ... 9.2還有其他選擇嗎? – Jayant

+0

查看編輯答案。 – klin

+0

我以同樣的方式做了它..想知道是否有任何替代橫向...非常感謝! – Jayant

0
CREATE OR replace FUNCTION fnn() 
RETURNS setof t1 AS $$ 
DECLARE sql TEXT; 
BEGIN 
    SELECT CASE 
      WHEN max < 10 
       THEN 'select ob1, ob2, istart, iend from t1' 
      WHEN max >= 50 
       THEN ' select ob1, ob2, istart, iend from t2;' 
      WHEN max > 10 
       THEN ' select ob1, ob2, istart, iend from t3;' 
      END AS qry 
    INTO sql 
    FROM itable; 
    RETURN QUERY 
    EXECUTE (sql); 
END $$ 
LANGUAGE plpgsql 

用法:

select * from fnn() 

DO $$ 
DECLARE sql TEXT; 
BEGIN 
    SELECT CASE 
      WHEN max < 10 
       THEN 'select ob1, ob2, istart, iend from t1' 
      WHEN max >= 50 
       THEN ' select ob1, ob2, istart, iend from t2;' 
      WHEN max > 10 
       THEN ' select ob1, ob2, istart, iend from t3;' 
      END AS qry 
    INTO sql 
    FROM itable; 
    DROP TABLE IF EXISTS t; 
    EXECUTE ('create temp table t as ' || sql); 
END $$; 

select * from t; 
相關問題