【发布时间】:2011-02-02 22:02:12
【问题描述】:
我有一个带有accounting_period 的表格,2011 年 1 月的 201101,2011 年 2 月的 201102 等。
我正在尝试对本季度的列 (eff_cc) 求和。也就是说,我想获取 2011 年 1 月、2 月和 3 月第一季度某个日期的数据总和,等等。
所以,我在 where 子句中使用了 Case 语句。基本上我说(在 where 子句中):
- 如果当前月份是1、4、7或10,则获取该月份的数据;
- 如果当前月份是2、5、8或11,则获取当前月份和上个月的数据;和
- 如果当前月份是 3、6、9 或 12,则获取当前和前两个月的数据
不想工作。代码如下。
select phase_code, accounting_period, sum(eff_cc) as BD_Eff_QTD,
from prj_detail
where
case month(getdate()) % 3
when 1 then -- current month is 1,4,7,10
accounting_period = right(Year(getDate()),4) + Right('0' + rtrim(month(getDate())),2)
when 2 then -- current month is 2, 5, 8, 11
(accounting_period = right(Year(getDate()),4) + Right('0' + rtrim(month(getDate())),2) or
accounting_period = right(Year(getDate()),4) + Right('0' + rtrim(month(getDate())-1),2))
when 3 then -- current month is 3, 6, 9, 12
(accounting_period = right(Year(getDate()),4) + Right('0' + rtrim(month(getDate())),2) or
accounting_period = right(Year(getDate()),4) + Right('0' + rtrim(month(getDate())-1),2) or
accounting_period = right(Year(getDate()),4) + Right('0' + rtrim(month(getDate())-2),2))
end
group by phase_code, accounting_period
【问题讨论】:
-
WHAT 数据库,哪个版本??
-
什么不起作用?您是否收到错误或无效数据?
-
我不明白,你为什么要和
GETDATE()比较?,输出取决于今天的日期?...你不只是想sum(eff_cc)为每个季度存储在您的餐桌上的日期? -
错误是“=”附近的语法不正确。基本上,我试图只获取季度至今的信息,而不是每个季度的信息。
-
@R Dev - 所以如果是 2 月,你想要 2 个月的结果,1 月、2 月的每个月一个吗?
标签: sql sql-server case where