【问题标题】:use strings in PostgreSQL as variables to find column names在 PostgreSQL 中使用字符串作为变量来查找列名
【发布时间】:2017-03-24 23:08:26
【问题描述】:

我有两张表,我想将它们加入其中并从一张表中查找以找到另一张表中的列标题。

一个表如下所示:

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

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

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    您可以使用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;
    

    【讨论】:

    • 有效!谢谢你。现在我正试图将它放入我更大的查询中并找到新的错误来解开。继续下一个 SO 帖子!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 2015-04-02
    相关资源
    最近更新 更多