代码之家  ›  专栏  ›  技术社区  ›  LCJ

在不考虑实际天数的情况下找出两者之间的月份

  •  0
  • LCJ  · 技术社区  · 7 年前

    CREATE TABLE #ServicePaymentCollection (ServiceID INT, ServiceDate DATE, ServiceAmount INT, 
                                            PaymentDate DATE, AmountPaid INT)
    INSERT INTO #ServicePaymentCollection
    SELECT 2, '2017-01-30', 1200, '2017-01-31', 50 UNION
    SELECT 2, '2017-01-30', 1200, '2017-02-01', 200 UNION
    SELECT 2, '2017-01-30', 1200, '2017-05-20', 200 UNION
    SELECT 2, '2017-01-30', 1200, '2017-11-20', 200 UNION
    SELECT 2, '2017-01-30', 1200, '2017-12-20', 200 UNION
    SELECT 2, '2017-01-30', 1200, '2018-01-10', 200 UNION
    SELECT 2, '2017-01-30', 1200, '2018-02-15', 150 
    

    我需要列出每行的月差。服务于2017年1月30日完成。第一次付款于2017年1月31日收到。对于该行,月差为0。

    第二次付款于2017年2月1日收到。对于此行,月差为1。

    以下查询工作正常,直到2017年改为2018年。2018年1月10日收到付款时,显示月差100。如何修复。

    SELECT *, (PaymentYearMonth - ServiceYearMonth) AS MonthDifference
    FROM
    (
        SELECT *,
                CONVERT(INT,(CONVERT(VARCHAR(20),YEAR(ServiceDate)) + RIGHT('00'+CONVERT(VARCHAR(20), MONTH(ServiceDate)),2)  )) ServiceYearMonth,
                CONVERT(INT,(CONVERT(VARCHAR(20),YEAR(PaymentDate)) + RIGHT('00'+CONVERT(VARCHAR(20), MONTH(PaymentDate)),2)  )) PaymentYearMonth 
        FROM #ServicePaymentCollection
    )T
    ORDER BY MonthDifference
    

    结果

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   jyao    7 年前

    我认为下面的查询将解决您的问题(我保留了您的原始代码,但添加了一个新列,以便您可以比较差异)

    SELECT *, (PaymentYearMonth - ServiceYearMonth) AS MonthDifference, newMonthDiff = datediff(month, ServiceDate, PaymentDate)
    FROM
    (
        SELECT *,
                CONVERT(INT,(CONVERT(VARCHAR(20),YEAR(ServiceDate)) + RIGHT('00'+CONVERT(VARCHAR(20), MONTH(ServiceDate)),2)  )) ServiceYearMonth,
                CONVERT(INT,(CONVERT(VARCHAR(20),YEAR(PaymentDate)) + RIGHT('00'+CONVERT(VARCHAR(20), MONTH(PaymentDate)),2)  )) PaymentYearMonth 
                --, ServiceDate, PaymentDate
        FROM #ServicePaymentCollection
    )T
    ORDER BY MonthDifference
    

    enter image description here