带前导零的月份的 SQL

问题描述 投票:0回答:1

我有以下查询要获取

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

我搜索了其他方式来编写这个查询

getdate
1个回答
0
投票
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()) 返回的当前月份进行比较。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.