我正在使用SQLServer2008。
SELECT Amount ,
OpportunityCloseDate
FROM dbo.OpportunityMaster AS om
,输出为:
Amount OpportunityCloseDate
------------------------------------
25458.00 2012-07-02 00:00:00.000
54555.00 2012-08-16 00:00:00.000
2154.00 2012-08-21 00:00:00.000
123458.00 2013-08-31 00:00:00.000
54546.00 2013-08-28 00:00:00.000
1235.00 2013-08-22 00:00:00.000
56454.00 2013-08-22 00:00:00.000
156.00 2013-09-13 00:00:00.000
34534.00 2013-09-04 00:00:00.000
34355.00 2013-09-02 00:00:00.000
76568.00 2013-09-01 00:00:00.000
235646.00 2013-09-10 00:00:00.000
54465.00 2013-09-18 00:00:00.000
244254.00 2013-12-19 00:00:00.000
预期产出:
Amount Quarter
------------------
82167.00 Q1
671417.00 Q2
244254.00 Q3
在我的数据库中,年份从4月1日开始。 我希望每季度获得这些数据。我不太了解季度。谢谢你的帮助..
答案 0 :(得分:1)
我假设您想要对每个季度的数据求和:
;With Totals as (
SELECT SUM(Amount) as Total,
DATEADD(quarter,DATEDIFF(quarter,0,OpportunityCloseDate),0) as RoundQuarter
FROM dbo.OpportunityMaster AS om
GROUP BY
DATEADD(quarter,DATEDIFF(quarter,0,OpportunityCloseDate),0)
)
select
Total,
DATEPART(year,RoundQuarter) -
CASE WHEN DATEPART(quarter,RoundQuarter) = 1 THEN 1 ELSE 0 END as FinancialYear,
CASE WHEN DATEPART(quarter,RoundQuarter) = 1 THEN 4
ELSE DATEPART(quarter,RoundQuarter) - 1 END as FinancialQuarter
from
Totals
这可以通过计算自1900-01-01
1 以来发生的(整数)季度数,然后将相同数量的季度添加到1900-01-01
。这样可以将每个日期四舍五入到每个季度的第一天。
datetime
时, 1 0被视为1900-01-01
。