I have this table:
ID | name | result |
--------------------
1 | A | 1 |
--------------------
2 | B | 2 |
--------------------
3 | C | 1 |
--------------------
1 | A | 2 |
--------------------
4 | E | 2 |
--------------------
I want to add a new temporary column next to |result|, and where result=1 the value should be 100, and where result=2 the value should be 80 so it should look like this:
ID | name | result | NewColumn|
-------------------------------
1 | A | 1 | 100 |
-------------------------------
2 | B | 2 | 80 |
-------------------------------
3 | C | 1 | 100 |
-------------------------------
1 | A | 2 | 80 |
-------------------------------
4 | E | 2 | 80 |
-------------------------------
How can I query this in SQL ?
As the answers given above are also correct. But I will say that if you have a predefined relation or logic between the existing column and the new column then you can also achieve that without the
CASE
. WritingCASE
for all the possible values would not be possible nor efficient.For your existing data. I can use it something like this
Here I am assuming that
1=>100
,2=>80
,3=>60
,4=>40
,5=>20
.of course this only for understanding purpose. You can create your own expression depending on the actual data.
You would use IF Statement in Mysql
SELECT col1,col2,col3, IF(col3=1,'100', IF(col3=2,80,'')) FROM your_table
Use a
CASE
expression in yourSELECT
's column list - something like this:Add additional
WHEN
expressions or alter theELSE
expression as needed.You could add a
case
statement to your query: