在连接的ON子句中使用大小写

问题描述 投票:0回答:2

我有一个问题:在JOIN的ON子句中使用CASE语句的正确方法是什么?(我看到其他人也问过几个类似的问题,但是我看不到如何在我的场景中复制解决方案。)

我尝试连接同一表的2个实例(自我加入)。该表包含每天每位客户的余额值(每位客户每天的行数,每位客户从活动的第一天开始直到他/她关闭帐户多次出现)

enter image description here

对于每个客户,我需要在今天和另一列中找到余额-“基准日”上的余额是多少。如果客户来自特定分支机构(“ X”分支),则基准日期的默认值为31 -dec-2019 BUT,则基准日期应为2020年3月31日(而非2019)。所以我想做的是写这样的东西:

select 
B.branch_name,
B.customer_id,
B.balance as current_balance,
B1.balance as base_date_balance,
from 
balance B inner join balance B1
on B.customer_id=B1.customer_id
and B.date = '20apr2020'
and B1.date= (case when B.branch_name = 'X' then '31-mar-2020' else '31-dec-2019' end)

我知道这不是执行此操作的正确方法,但是我无法弄清楚什么是正确的方法。在此先感谢您提供的所有答案和帮助,非常感谢! :)

sql self-join
2个回答
0
投票

使用窗口功能!:

select b.*,
       max(case when branch = 'B' and date = date '2019-03-31' then balance
                when date = date '2019-12-31' then balance
           end) over (partition by customer_id, branch_name
                     ) as base_date_balance
from balance b;

与具有JOINOR条件的CASE相比,它应具有更好的性能。

或者,join看起来像:

from b join
     b bbase
     on bbase.customer_id = b.customer_id and
        bbase.branch_name = b.branch_name and
        ( (bbase.branch_name = 'B' and bbase.date = date '2019-03-31') or
          (bbase.branch_name <> 'B' and bbase.date = date '2019-12-31')
        )

0
投票

从其中rownum = 1和日期的表中选择b。*

这将根据条件为您提供上一笔交易。子查询返回最新的事务。

下一步将取决于数据库。在Oracle上,您使用:

从双中选择(选择最新交易)-(选择先前交易)。>

如果您需要更多信息,请告诉我。我正在用手机写信。

© www.soinside.com 2019 - 2024. All rights reserved.