我有一张桌子:tblperson
tblperson
中有三列id amort_date total_amort
C000000004 12/30/2015 4584.00
C000000004 01/31/2016 4584.00
C000000004 02/28/2016 4584.00
用户必须提供结算日期@bill_date
我想将所有总和的总和少于总和少于用户按月和年度给出的日期,而不管日期
例如
@bill_date = '1/16/2016'
Result should:
ID sum_total_amort
C000000004 9168.00
无论日期我想要比2016年1月所有的总和还要多
这是我的查询,但它只计算2016年1月的日期,它不包括小于它的日期:
DECLARE @bill_date DATE
SET @bill_date='1/20/2016'
DECLARE @month AS INT=MONTH(@bill_date)
DECLARE @year AS INT=YEAR(@bill_date)
SELECT id,sum(total_amort)as'sum_total_amort' FROM webloan.dbo.amort_guide
WHERE loan_no='C000000004'
AND MONTH(amort_date) = @month
AND YEAR(amort_date) = @year
GROUP BY id
答案 0 :(得分:2)
你会使用聚合和不等式:
select id, sum(total_amort)
from webloan.dbo.amort_guide
where loan_no = 'C000000004' and
year(amort_date) * 12 + month(amort_date) <= @year * 12 + @month
group by id;
或者,在SQL Server 2012+中,您可以使用EOMONTH()
:
select id, sum(total_amort)
from webloan.dbo.amort_guide
where loan_no = 'C000000004' and
amort_date <= EOMONTH(@bill_date)
group by id;
答案 1 :(得分:1)
您可以使用以下方式获取月初:
DATEADD(MONTH, DATEDIFF(MONTH, 0, @bill_date), 0)
所以要获得SUM(total_amort)
,您的查询应为:
SELECT
id,
SUM(total_amort) AS sum_total_amort
FROM webloan.dbo.amort_guide
WHERE
loan_no='C000000004'
AND amort_date < DATEADD(MONTH, DATEDIFF(MONTH, 0, @bill_date) + 1, 0)
答案 2 :(得分:0)
您正在检查
AND MONTH(amort_date) < @month
AND YEAR(amort_date) < @year
因此,查询将仅返回MONTH(amort_date)=MONTH(input_variable) AND YEAR(amort_date)=YEAR(input_variable)
试试这个 DECLARE @bill_date日期 SET @ bill_date ='1/20 / 2016'
DECLARE @month AS INT=MONTH(@bill_date)
DECLARE @year AS INT=YEAR(@bill_date)
SELECT id,sum(total_amort)as'sum_total_amort' FROM webloan.dbo.amort_guide
WHERE loan_no='C000000004'
AND MONTH(amort_date) < @month
AND YEAR(amort_date) < @year
GROUP BY id