当我运行此查询时,它在2015-4-11日期运行时似乎运行良好。但是,如果我查询过去3天,它会返回年,月和周的值。这一天是准确的,但它似乎没有正确地添加其他所有内容。
declare @today date = '2015-1-1'
select
[Day Total] = sum(case when [AccountingDate] < dateadd(DAY, 1, @today) then [Amount] else 0 end),
[Week Total] = sum(case when [AccountingDate] < dateadd(WEEK, 1, @today) then [Amount] else 0 end),
[Month Total] = sum(case when [AccountingDate] < dateadd(MONTH, 1, @today) then [Amount] else 0 end),
[Year Total] = sum([Amount])
from
[Accounting].[dbo].[HandPay]
where
[AccountingDate] >= @today and [AccountingDate] < dateadd(year, 1, @today);
答案 0 :(得分:1)
当您使用最近的日期时,您正在寻找[AccountingDate]
小于某个未来日期的值。
如果您将今日/周/月添加到今天,那么除非您的表中有未来数据,否则所有数据都将在这些日期之前:
declare @today date = '2015-05-12'
SELECT dateadd(DAY, 1, @today)
,dateadd(week, 1, @today)
,dateadd(month, 1, @today)
返回:2015-05-13, 2015-05-19, 2015-06-12
因此,如果您的表格仅包含今天的数据,那么[AccountingDate]
总是小于这些日期。
如果您确实希望从今天到1天,1周前和1个月后汇总,则需要在-1
中使用DATEADD()
,使用>
,修改您的WHERE
条件,例如:
declare @today date = '2015-1-1'
select
[Day Total] = sum(case when [AccountingDate] > dateadd(DAY, -1, @today) then [Amount] else 0 end),
[Week Total] = sum(case when [AccountingDate] > dateadd(WEEK, -1, @today) then [Amount] else 0 end),
[Month Total] = sum(case when [AccountingDate] > dateadd(MONTH, -1, @today) then [Amount] else 0 end),
[Year Total] = sum([Amount])
from
[Accounting].[dbo].[HandPay]
where
[AccountingDate] <= @today and [AccountingDate] > dateadd(MONTH, -1, @today);
注意:在午夜之后的任何时间将DATETIME
与DATE
进行比较时,我们会将其视为大于DATE
值,因此您需要确保不排除通过将DATETIME
强制转换为DATE
或确保您已正确考虑范围,即:&lt;明天的DATE
代替&lt; =今天的DATE
,以包含今天有00:00:00.000