Kushal LNU
Kushal LNU

Reputation: 59

How to write a query for this scenario

I have a table like below in PostgreSQL.

+-------+--------+----------+--------+
|id     | name   |  rate    | amount |
+-------+--------+----------+--------+
|123    | Flat   |          | 40     |
|123    | weekly | 200      |        |
+-------+--------+----------+--------+

I need to show amount when its flat and rate when its weekly in the 'name' column. Expecting output like this:

+-------+-------+-----------+--------+
| id    | name  |  rate     | amount |
+-------+-------+-----------+--------+
| 123   | 40    |           | 40     |
| 123   | 200   | 200       |        |
+-------+-------+-----------+--------+

Is it doable in PostgreSQL. If yes, how to do it.

Upvotes: 1

Views: 35

Answers (1)

Fabricator
Fabricator

Reputation: 12772

Use a CASE expression:

SELECT id, CASE WHEN name = 'Flat' THEN amount ELSE rate END AS name, rate, amount
FROM mytable

Upvotes: 1

Related Questions