我有以下查询要获取
SELECT EntityID, LatestAmortizationMonth, LatestAmortizationYear, SUM(FacilityValueOriginal) AS Original, SUM(PrincipalPaymentToDate) AS PrincipalPmt, SUM(InterestPaymentToDate) AS InterestPmt, SUM(FacilityValueCurrent) AS CurrentBal, 货币 来自 dbo.commercial_loanss GROUP BY EntityID、LatestAmortizationMonth、LatestAmortizationYear、货币 具有 (LatestAmortizationMonth = DATENAME(MONTH, GETDATE())) 和 (LatestAmortizationYear = DATENAME(YEAR, GETDATE()))
然而,我的月度值从 1 月到 9 月以前导零存储,即 01、02、03 等。
由于 DATENAME(MONTH, GETDATE())) 返回 1,2,3 等,上述查询不适用于 Jan 到 Sept
我搜索了其他方式来编写这个查询
SELECT EntityID,
RIGHT('0' + CAST(LatestAmortizationMonth AS VARCHAR(2)), 2) AS LatestAmortizationMonth,
LatestAmortizationYear,
SUM(FacilityValueOriginal) AS Original,
SUM(PrincipalPaymentToDate) AS PrincipalPmt,
SUM(InterestPaymentToDate) AS InterestPmt,
SUM(FacilityValueCurrent) AS CurrentBal,
currency
FROM dbo.commercial_loanss
GROUP BY EntityID,
LatestAmortizationMonth,
LatestAmortizationYear,
currency
HAVING (LatestAmortizationMonth = RIGHT('0' + CAST(MONTH(GETDATE()) AS VARCHAR(2)), 2))
AND (LatestAmortizationYear = YEAR(GETDATE()))
此查询会将 LatestAmortizationMonth 列转换为带前导零的字符串,并将其与 MONTH(GETDATE()) 返回的当前月份进行比较。