[英]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.