IF EXISTS(SELECT * FROM sys.tables WHERE name='tblSample__')
DROP TABLE dbo.tblSample__
Go
CREATE TABLE dbo.tblSample__(report_date DATETIME,interest DECIMAL(18,2))
GO
INSERT INTO dbo.tblSample__
SELECT '2021/01/01 23:59:59', 1
UNION
SELECT '2021/01/02 21:00:00', 5
UNION
SELECT '2021/01/03 23:59:59', 1
UNION
SELECT '2021/02/01', 6
UNION
SELECT '2021/02/02', 10
UNION
SELECT '2021/03/01', 12
GO
IF NOT OBJECT_ID('TempDB..#T') IS Null
DROP TABLE #T
Go
SELECT *
,DATEADD(month, DATEDIFF(month, 0, report_date), 0) AS StartOfMonth
,DATEADD(mm, DATEDIFF(mm, 0, report_date) + 1, 0)LastOfNextMonth
INTO #T
FROM dbo.tblSample__ t
GO
SELECT * FROM #T
GO
SELECT * ,
(SELECT SUM(ISNULL(interest,0))
FROM #T tmp
WHERE
s.report_date >= tmp.StartOfMonth
AND s.report_date < tmp.LastOfNextMonth
AND s.report_date >=tmp.report_date)
FROM dbo.tblSample__ s
或
SELECT * ,
(SELECT SUM(ISNULL(interest,0))
FROM (
SELECT *
,DATEADD(month, DATEDIFF(month, 0, report_date), 0) AS StartOfMonth
,DATEADD(mm, DATEDIFF(mm, 0, report_date) + 1, 0)LastOfNextMonth
FROM dbo.tblSample__ t
) tmp
WHERE
s.report_date >= tmp.StartOfMonth
AND s.report_date < tmp.LastOfNextMonth
AND s.report_date >=tmp.report_date)
FROM dbo.tblSample__ s
或
SELECT * ,
(SELECT SUM(ISNULL(interest,0))
FROM (
SELECT *
,DATEADD(month, DATEDIFF(month, 0, report_date), 0) AS StartOfMonth
,DATEADD(mm, DATEDIFF(mm, 0, report_date) + 1, 0)LastOfNextMonth
FROM dbo.tblSample__ t
WHERE s.report_date >=t.report_date
) tmp
WHERE
s.report_date >= tmp.StartOfMonth
AND s.report_date < tmp.LastOfNextMonth
)
FROM dbo.tblSample__ s