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
结果