使用PostgreSQL中的字符串作为变量来查找列名

时间:2017-03-24 14:42:22

标签: 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 .... //;' 
 }

我一直在尝试在文档和搜索中找到相关帮助,但不确定如何最好地设置我的查询。

1 个答案:

答案 0 :(得分: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;