简体   繁体   中英

Return value corresponding to date

I need this table with dates and values according the cost per day

day        | cost_day
-------------------------
2019-11-17 | 25
2019-11-18 | 20
null       | 10

I need that return cost 25 for day 2019-11-17 or cost 20 for day 2019-11-18 or cost 10 for others days like 2019-11-19 or 2019-11-20.

I tried this queries:

SELECT day, cost_day 
FROM table WHERE day = COALESCE('2019-11-19', null::date) 

This return correct for days 2019-11-17 and 2019-11-18, but return null for others days, like 2019-11-19.

SELECT day, cost_day 
FROM table WHERE (day = '2019-11-19' OR day is null)

This return correct for other days that not included in the table but for days in the table like 2019-11-18, the query return two costs values. The value for the specific date and the value for null date.

I need this return just one value, because I will use this query like a subquery.

Can someone help me?

edit:

I need return the date found too. Example: If I found 2019-11-19, I need return day 2019-11-19 and cost_day 10.

How about this?

select cost_day
from t
where day is null or day = '2019-11-19'
order by (day is not null) desc;

EDIT:

select coalesce(day, '2019-11-19') cost_day
from t
where day is null or day = '2019-11-19'
order by (day is not null) desc;

You can use COALESCE() with 2 queries for both cases:

SELECT '2019-11-19'::DATE "day", 
  COALESCE(
    (SELECT cost_day FROM tablename WHERE day = '2019-11-19'::DATE),
    (SELECT cost_day FROM tablename WHERE day IS NULL)
  ) cost_day 

See the demo .
Results:

| day        | cost_day |
| ---------- | -------- |
| 2019-11-19 | 10       |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM