2017-04-12 49 views
0

例如起見,有五列在一個表中monthPostgres的選擇串聯列名

  • month.week1
  • month.week2
  • month.week3
  • month.week4
  • month.week5

的數量通過函數

EXTRACT(WEEK FROM NOW()) - EXTRACT(WEEK FROM DATE_TRUNC('month', NOW())) + 1

如何選擇列colX確定的?這是我迄今爲止

SELECT month.week || (
    EXTRACT(WEEK FROM NOW()) 
    - EXTRACT(WEEK FROM DATE_TRUNC('month', NOW())) + 1 
)::text 
FROM month 

但是,這給我的錯誤

ERROR: column month.week doesn't exist SQL state: 42703

回答

3

使用case語句

SELECT 
    CASE WHEN (week expresion) = 1 THEN month.week1 
     WHEN (week expresion) = 2 THEN month.week2 
     WHEN (week expresion) = 3 THEN month.week3 
     WHEN (week expresion) = 4 THEN month.week4 
     ELSE month.week5 
    END as WeekValue 
FROM month 

OR

SELECT 
    CASE (week expresion) 
     WHEN 1 THEN month.week1 
     WHEN 2 THEN month.week2 
     WHEN 3 THEN month.week3 
     WHEN 4 THEN month.week4 
     ELSE month.week5 
    END as WeekValue 
FROM month 
+2

或者僅僅是'CASE(周表達式)當1那麼...當2 ...'爲了避免重複(真的很長)周表達式。 – pozs

0

動態SQL樣本:

t=# create table so58(i int,w1 text); 
CREATE TABLE 
t=# create or replace function so59(_n int) returns table (i int,w text) as $$begin 
return query execute format('select i,w%s from so58',_n); 
end; 
$$ language plpgsql; 
CREATE FUNCTION 
t=# select * from so59(1); 
i | w 
---+--- 
(0 rows)