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

后端 未结 3 2025
孤街浪徒
孤街浪徒 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:43

    Important note: I would create a view based on your current table and avoided adding new columns, as they will denormalize your schema. Read more here.

    Also, I will use lowercase names for all the identifiers to avoid qouting.

    • to form GPA_TXT field you can use to_char() function: to_char(gpa, 'FM09.0') (the FM will avoid space in front of the resulting string);
    • for the second field, I would use GPA and not GPA_TXT for numeric comparison. You can check more on CASE construct in the docs, but the block might be the following one:

      CASE WHEN gpa >= 3.3 THEN 'A'
           WHEN gpa > 2.7 AND gpa < 3.3 THEN 'B'
           WHEN gpa > 0 THEN 'C'
           ELSE 'F' END
      

    Sorry, I don't know how grades are assigned per GPA, please, adjust accordingly.

    The resulting query for the view might be (also on SQL Fiddle):

    SELECT name,major,gpa,
           to_char(gpa, 'FM09.0') AS gpa_txt,
           name||'-'||major||'-Grade'||
      CASE WHEN gpa >= 3.3 THEN 'A'
           WHEN gpa > 2.7 AND gpa < 3.3 THEN 'B'
           WHEN gpa > 0 THEN 'C'
           ELSE 'F' END || '-' || to_char(gpa, 'FM09.0') AS adesc
      FROM atab;
    

    To build a view just prepend CREATE VIEW aview AS before this query.


    EDIT

    If you still go for adding columns, the following should do the trick:

    ALTER TABLE atab ADD gpa_txt text, ADD adesc text;
    UPDATE atab SET
        gpa_txt = to_char(gpa, 'FM09.0'),
        adesc = name||'-'||major||'-Grade'||
          CASE WHEN gpa >= 3.3 THEN 'A'
               WHEN gpa > 2.7 AND gpa < 3.3 THEN 'B'
               WHEN gpa > 0 THEN 'C'
               ELSE 'F' END || '-' || to_char(gpa, 'FM09.0');
    

提交回复
热议问题