简体   繁体   English

返回日期对应的值

[英]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.我需要 2019-11-17 天的退货成本 25 或 2019-11-18 天的成本 20 或其他日子(如 2019-11-19 或 2019-11-20)的成本 10。

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.此返回对于 2019-11-17 和 2019-11-18 天是正确的,但对于其他天返回 null,例如 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.此返回对于未包含在表中的其他天数是正确的,但对于表中的天数(如 2019-11-18),查询返回两个成本值。 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.示例:如果我找到 2019-11-19,我需要返回日期 2019-11-19 和 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:对于这两种情况,您都可以将COALESCE()与 2 个查询一起使用:

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       |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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