2017-03-24 27 views
0

我有两个表,我想要加入他们,并从一个查找另一个查找列标题。在PostgreSQL中使用字符串作为变量来查找列名称

一个表是这样的:

table: student_score    
student| red |blue |green 
------- -------- ------- ----- 
201 | 88 |89  |78 
345 | 67 |72  |95 
987 | 75 |81  |89 

另一种是这样的:

table: student_history 
student | color_last_year 
------- ----------------- 
201  | red 
345  | blue 
987  | green 

我期待在PostgreSQL中创建一个查询,让我来接去年的颜色(来自历史记录表)作为分数表中的列标题。在过去,我使用JavaScript来做到这一点,但宁愿在一个psql查询中完成。

JS的看起来是这样的:

function lastYear(color){ 
var query = 'SELECT student_score.' + color + ' 
    FROM student_score 
    JOIN student_score ON student_score.student = 
    student_history.student 
    //...more code .... //;' 
} 

我一直试图找到解决这个帮助文档和搜索,但不知道如何以最佳方式设置我的查询。

回答

3

可以使用case表达:

select 
    s.student, 
    case h.color_last_year 
     when 'red' then s.red 
     when 'blue' then s.blue 
     when 'green' then s.green 
    end as val 
from student_score s 
join student_history h on s.student = h.student; 
+0

作品!谢谢。现在我试图将其纳入我的更大的查询中,并找出新的错误来解决。继续到下一个SO帖子! – edswartz