繁体   English   中英

返回日期对应的值

[英]Return value corresponding to date

我需要这个包含日期和值的表,根据每天的成本

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

我需要 2019-11-17 天的退货成本 25 或 2019-11-18 天的成本 20 或其他日子(如 2019-11-19 或 2019-11-20)的成本 10。

我试过这个查询:

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

此返回对于 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)

此返回对于未包含在表中的其他天数是正确的,但对于表中的天数(如 2019-11-18),查询返回两个成本值。 特定日期的值和空日期的值。

我只需要返回一个值,因为我会像使用子查询一样使用这个查询。

有人能帮我吗?

编辑:

我也需要返回找到的日期。 示例:如果我找到 2019-11-19,我需要返回日期 2019-11-19 和 cost_day 10。

这个怎么样?

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

编辑:

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;

对于这两种情况,您都可以将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 

请参阅演示
结果:

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

暂无
暂无

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

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