我道歉,如果类似的问题在VB.Net已经问了RANK()和CASE WHEN。
我有两个表。 与所需的列脚本低于:
表格1:
SELECT S.* INTO dbo.LoanHeader
FROM
(
SELECT 1 LoanHeaderId, 1234 LoanNumber, GETDATE() EffectiveOn
UNION ALL
SELECT 2 LoanHeaderId, 2234 LoanNumber, GETDATE() EffectiveOn
UNION ALL
SELECT 3 LoanHeaderId, 3234 LoanNumber, GETDATE() EffectiveOn
)S
表2:
SELECT S.* INTO dbo.LoanHeaderHistory
FROM
(
SELECT 1 LoanHeaderId, 1 NewValue, 'LoanReviewStatusId' ColumnName, DATEADD(DD, -3, GETDATE()) EnteredDate
UNION ALL
SELECT 1 LoanHeaderId, 2 NewValue, 'LoanReviewStatusId' ColumnName, DATEADD(DD, -2, GETDATE()) EnteredDate
UNION ALL
SELECT 1 LoanHeaderId, 3 NewValue, 'LoanReviewStatusId' ColumnName, DATEADD(DD, -1, GETDATE()) EnteredDate
UNION ALL
SELECT 1 LoanHeaderId, 1 NewValue, 'LoanReviewStatusId' ColumnName, GETDATE() EnteredDate
)S
我想在下面的SQL的VB.Net写一个LINQ声明 。 这里涉及其他表,如果我开始说为什么我需要它这样会花费太长的时间。 但我们的目的是使用标准的基础上的NewValue日期之一:
SELECT
LH.LoanHeaderId,
LHH.NewValue,
LHH.EnteredDate
FROM dbo.LoanHeader LH
LEFT JOIN
(
SELECT
LoanHeaderId,
NewValue,
EnteredDate,
RANK() OVER (PARTITION BY LoanHeaderId ORDER BY EnteredDate DESC) HRank
FROM dbo.LoanHeaderHistory
WHERE ColumnName = 'LoanReviewStatusId'
)LHH ON LHH.LoanHeaderId = LH.LoanHeaderId AND LHH.HRank = 1
WHERE CASE WHEN ISNULL(LHH.NewValue, 1) IN (2, 3) THEN LHH.EnteredDate ELSE LH.EffectiveOn END >= LH.EffectiveOn
我开始做这种方式:
Dim columnName = "LoanReviewStatusId"
Dim query = (From lh In e.LoanHeaderEntities_
From lhh In e.LoanHeaderHistoryEntities.OrderByDescending(Function(i) i.EnteredDate).Where(Function(i) lh.LoanHeaderId = i.LoanHeaderId AndAlso i.ColumnName = columnName).DefaultIfEmpty() _
Select New With{ _
lh.LoanHeaderId, _
lhh.NewValue, _
lhh.EnteredDate _
})
query = query.Where(Function(i) If(Not IsNothing(i.LoanReviewStatusId) AndAlso (i.LoanReviewStatusId = 2 Or i.LoanReviewStatusId = 3), i.LoanStatusChangedDate, i.EffectiveOn) >= i.EffectiveOn)
Return query.ToList()