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 if/when syntax I’d use to help create the following fields (GPA_TXT, and newfield)?
The logic is: Each GPA should be #.#, each new field should be:
name & "-" & GPA_TXT & (
case where GPA_TXT > 3.3
set newfield = newfield & 'GradeA',
case where GPA_TXT >2.7 and GPA_TXT < 3.3
set newfield = newfield & "GradeB",
etc...
)
For example:
name major GPA(num) GPA_TXT [newfield]
Bob sci 2 02.0 Bob-sci-GradeC-02.0
Jane chem 3.1 03.1 Jane-chem-GradeB-03.1
Charlie phys 3.7 03.7 Charlie-phys-GradeA-03.7
Garfield food 0 00.0 Garfield-food-GradeF-00.0
So I guess I have two questions in here:
- How to create the GPA TXT field.
- How to write a case statement to calculate a field according to the values in other fields.
If anyone can link me to a resource with examples or explain I would greatly appreciate it! I’m looking through the documentation but not getting anywhere without examples.
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.
GPA_TXTfield you can useto_char()function:to_char(gpa, 'FM09.0')(theFMwill avoid space in front of the resulting string);for the second field, I would use
GPAand notGPA_TXTfor numeric comparison. You can check more onCASEconstruct in the docs, but the block might be the following one: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):
To build a view just prepend
CREATE VIEW aview ASbefore this query.EDIT
If you still go for adding columns, the following should do the trick: