在两个日期之间添加sql

时间:2015-08-30 02:57:59

标签: sql sql-server tsql

我有一个SQL查询,它获取两个日期之间的总和,但只有当它们具有相同的年份时才会这样。

SELECT 
    [Purchased Product], 
    SUM(CONVERT(INT, [Purchased Quantity])) AS [Quantity]  
FROM 
    StudentPurchasedHistoryTable 
WHERE 
    DATENAME(month, [Purchased Date]) BETWEEN 'july' AND 'may' 
GROUP BY 
    [Purchased Product]

如何获得两个日期之间的总和,但现在它来自去年的月份?

例如今年7月至去年5月之间。

1 个答案:

答案 0 :(得分:2)

您可以声明2个变量并根据需要进行更改,以便获得预期的查询结果。或者在where子句中明确地对它们进行硬编码。建议您不要使用datename。请改用datepart()

declare @startdate date = '20140501';
declare @enddate date = '20150731';

SELECT [Purchased Product], sum(CONVERT(INT,[Purchased Quantity])) as [Quantity]  
From StudentPurchasedHistoryTable 
WHERE [Purchased Date] between @startdate and @enddate
Group By [Purchased Product]