1

我有 2 张桌子t1(id,send_date,volume)t2(send_date,rate). 当两个日期匹配时,我需要加入这两个表并从 t2 获取速率。

select t1.id, t1.volume * t2.rate 
from t1, t2 
where t1.send_date = t2.send_date

现在,我的要求是,如果表 t2 中没有与 t1 中的日期匹配的日期,并且如果 t1 中的日期是 SUNDAY,那么我需要获取下周一的汇率。

例如:如果 2013 年 2 月 10 日不在 t2 中,则 2 月 11 日的汇率应用于 t1 中的 2 月 10 日

问候,

萨西

4

1 回答 1

0

以下是我的查询和您的回答:

SELECT * -- Select all or any column that you want.
  FROM t2 JOIN (
  SELECT id
         , CASE
             WHEN TO_CHAR(send_date, 'DAY')
                  = TO_CHAR(TO_DATE('03-MAR-2013'), 'DAY')
                  -- The above condition returns true if send_date is a sunday
                  -- as '03-MAR-2013' is a sunday.
                  AND (SELECT COUNT(*)
                         FROM t2
                        WHERE t2.send_date = t1.send_date) = 0
                  -- This condition checks if any matching row exists
                  -- in t2 for the send_date.
             THEN send_date + 1  -- Increments the day by 1 to fetch
                                 -- the rates for a monday.
             Else send_date -- Leaves the send_date as it is for a normal date.
           END AS send_date
         , volume
    FROM t1
    ) USING (send_date) -- You can also use ON keyword to perform the join.
;

是供您参考的 SQLFiddle 示例。

于 2013-03-18T19:06:24.697 回答