我怎样才能得到我在这里寻找的东西?

时间:2015-12-04 15:05:41

标签: sql-server tsql date

我认为这个问题已经得到了回答,但是我还不够熟练(但是!)已经认识到别人的回答将如何帮助我解决我的问题,所以如果这感觉就像转发,我会道歉。

我正在使用MS Server2012

我需要查询中的以下结果:

  

LoanNumber | OpenDate | CreditLimit | CaptureDate | CaptureBalance |今天日期| TodayBalance

LoanNumber是唯一标识符| OpenDate是信用额度开放的日期CaptureDate是OpenDate + 6天| CaptureBalance是我们认为是信用额度的初始余额,并在其开放后6天定义为余额今天是今天的日子TodayBalance今天是平衡

我希望能够查看信用额度并将初始余额(即CaptureBalance)与信用额度进行比较,并将其与余额进行比较。

这是我的代码,请参阅下面的更多定义

select top 100
 L1.LOANNUMBER      as 'LoanNumber'
,L1.OPENDATE        as 'OpenDate' --this is stored as Date
,L2.OPENDATE+6      as 'CaptureDate'
,L1.CREDITLIMIT     as 'CreditLimit'
,(  Select L2.BALANCE
    From LOAN as L2
    INNER JOIN LOAN as L1 on L2.LOANNUMBER = L1.LOANNUMBER
    Where CONVERT(datetime,convert(char(8),L2.RUNDATE )) = L2.OPENDATE+6
    ) as 'CaptureBalance'

From LOAN as L1
INNER JOIN LOAN as L2 on L1.LOANNUMBER = L2.LOANNUMBER

Where L1.RUNDATE = 20151130  -- this is stored as INT
and L1.[TYPE] = 'Line of Credit'

RUNDATE非常重要,因为我们的系统每天都会记录一笔贷款。 Where L1.RUNDATE = 20151130告诉系统在2015年11月30日给我余额。我还需要在贷款开通日期后6天获得余额,这样我就可以参考2个不同的运行日期。

我必须将运行日期(INT)与OpenDate(日期)进行比较,因此我使用CONVERT(datetime,convert(char(8),L2.RUNDATE ))转换运行日期INT - >日期,以便我可以有效地比较两个日期。

当我跑步时,我得到:

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

最初我在同一张桌子上运行所有这些。然后我决定尝试给贷款表2个不同的别名,这就是我停下来的地方。

我使用该子查询的方式是否导致“超过1个值”,因为该查询的每个结果都试图列为列标题?如果是的话,我仍然不知道如何得到我正在寻找的东西。

HELP!?

1 个答案:

答案 0 :(得分:1)

我很确定这是你想要的,或者至少有一种方法:

select top 100
 L1.LOANNUMBER      as 'LoanNumber'
,L1.OPENDATE        as 'OpenDate' --this is stored as Date
,L2.RUNDATE      as 'CaptureDate'
,L1.CREDITLIMIT     as 'CreditLimit'
,L2.BALANCE as 'CaptureBalance'
,L1.RUNDATE as 'TodayDate'
,L1.BALANCE as 'TodayBalance'

From LOAN as L1
INNER JOIN LOAN as L2 
  on L1.LOANNUMBER = L2.LOANNUMBER
  AND L2.RUNDATE=DATEADD(dd, 6, L1.OPENDATE)

Where L1.RUNDATE = 20151130  -- this is stored as INT
and L1.[TYPE] = 'Line of Credit'