【问题标题】:Using Case Statement to compare four columns and adding the earliest date to the new column使用 Case Statement 比较四列并将最早日期添加到新列
【发布时间】:2021-01-26 00:46:00
【问题描述】:

我正在尝试创建一个列,列出四列中最早的日期。我已经尝试过这个案例声明和一个应该列出 s.Open_date 的罐子,而是将 2020 年 1 月 1 日放在列中。这是数据

tin     S.Open_Date     LoanOpen    CCOpenDate    MortgageDate    EarliestDate
1        5/5/2015        11/19/2018    null        9/25/2017         1/1/2020

所以在上面的例子中,EarliestDate 列中应该有 5/5/2015。

我已将整个查询放在下面。也就是说,查询中的所有内容都可以正常工作,除了 Case 语句。有更好的方法吗?

select i.mem, min(s.open_date) as ShareOpenDate, min(l.loanopen) as LoanOpen, min(ecc.cc_opendate) as CCopenDate, min(m.MortgageDate) as MortgageDate,

Case
when (s.open_date > l.loanopen and s.open_date > ecc.cc_opendate AND s.open_date > m.MortgageDate) then s.open_date
when (l.loanopen > s.open_date and l.loanopen > ecc.cc_opendate AND l.loanopen > m.MortgageDate) then l.loanopen
when (ecc.cc_opendate > s.open_date and ecc.cc_opendate > l.loanopen AND ecc.cc_opendate > m.MortgageDate) then ecc.cc_opendate
when (m.MortgageDate > s.open_date and m.MortgageDate > l.loanopen AND m.MortgageDate > ecc.cc_opendate) then m.MortgageDate
else '1/1/2020' END as EarliestDate

from individual as i
inner join membershipparticipant as mp on i.individual_id=mp.individual_id and mp.participation_type=101
inner join share as s on mp.member_nbr=s.member_nbr

#Subquery to bring in loan information
left outer join (
select member_nbr, min(open_date) as loanopen
from loan as l
group by member_nbr
)l  on s.member_nbr=l.member_nbr

#Subquery to bring in CC Information
left outer join ( 
select savings_acct_nbr, min(open_date) as cc_opendate
from externalcreditcard
group by savings_acct_nbr
) ecc on s.member_nbr=ecc.savings_acct_nbr

Subquery to bring in mortgage information
left outer join (
select MC_PMT_MBR_NBR as MortgageMember, min(MC_Loan_Date) as MortgageDate
from EXTERNALMORTGAGEMC
group by MC_PMT_MBR_NBR
)m on s.member_nbr=m.MortgageMember

group by i.mem

【问题讨论】:

  • case 是一个表达式,而不是statement

标签: sql sql-server


【解决方案1】:

最简单的方法是在SELECT 中使用子查询,尽管可能对性能有一点影响:

SELECT
...
, (SELECT MIN(x)
    FROM (VALUES
      (l.loanopen),
      (s.open_date),
      (ecc.cc_opendate),
      (m.MortgageDate),
      ('1/1/2020')
   ) AS v (x)) AS EarliestDate
FROM ...

【讨论】:

    猜你喜欢
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    相关资源
    最近更新 更多