我有一个基于ID的联接表,但我只想加入具有该ID最大“PeriodDT”(日期时间列)的行。
我已尝试使用“PeriodDT”的前1个订单,但它只会让我选择一列或我收到错误:
当选择列表中只能指定一个表达式时 子查询不是用EXISTS引入的
这是我使用的查询:
Select a.Name as PropertyName,
a.PropertyNum as PropertyNum,
a.City as City,
a.State as State,
b.Name as LoanName,
b.LoanNum,
(select Top 1 c.IntRate as IntRate,
c.MaturityDT
from vNoteDetail c where c.LoanID = b.LoanID Order By c.PeriodDT DESC)
from vProperty a join vLoan b on a.LoanID = b.LoanId
有更好的方法吗?
答案 0 :(得分:0)
试试这个..
;WITH cte
AS (SELECT Row_number() OVER(partition BY clientid ORDER BY perioddt DESC) rn,
intrate,
perioddt MaturityDT,
loanid
FROM vnotedetail)
SELECT a.NAME AS PropertyName,
a.propertynum AS PropertyNum,
a.city AS City,
a.state AS State,
b.NAME AS LoanName,
b.loannum,
c.intrate,
c.maturitydt,
FROM vproperty a
JOIN vloan b
ON a.loanid = b.loanid
JOIN cte c
ON c.loanid = b.loanid
WHERE c.rn = 1
子查询CHECK THIS
的FYI限制答案 1 :(得分:0)
尝试
Select a.Name as PropertyName,
a.PropertyNum as PropertyNum,
a.City as City,
a.State as State,
b.Name as LoanName,
b.LoanNum,
v1.IntRate,
v1.MaturityDT
from vProperty a join vLoan b on a.LoanID = b.LoanId
CROSS APPLY (select Top 1 c.IntRate as IntRate,
c.MaturityDT
from vNoteDetail c where c.LoanID = b.LoanID Order By c.PeriodDT DESC) AS V1