How can I create a column in postgres from values and selections based on other columns?

后端 未结 3 2069
孤街浪徒
孤街浪徒 2021-02-07 13:21

I want to create a new field (or two) in my table that is a concatenation of other fields, which seems relatively straightforward. But what is the case syntax or

3条回答
  •  半阙折子戏
    2021-02-07 13:54

    here is query that returns your values from a table with 3 columns:

    select *
    , to_char(gpa, '09.9') as gpa_text
    , name || '-' || major || '-Grade' ||
    case    when gpa between 3.5 and 4.0 then 'A'
        when gpa between 2.5 and 3.4 then 'B'
        when gpa between 1.5 and 2.4 then 'C'
        when gpa between 0.5 and 1.4 then 'D'
        else 'F' end
    || '-' || ltrim(to_char(gpa, '09.9')) as newfield
    from students
    

    This is working code, here is the newfield for Bob, "Bob-sci-GradeC-02.0"

    I would strongly suggest that you do not have a text column in a database to hold a duplicate of a numeric value. I'm not quite sure why I need the ltrim, it seems odd that the formatted string would have a leading blank.

提交回复
热议问题