0

我正在使用 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 日开始。我想按季度获取此数据。我不太了解季度..谢谢您的帮助..

4

1 回答 1

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

DATEADD

1900-01-01这是通过计算出自1以来出现的(整数)个季度数,然后将相同数量的季度数加到 上来实现的1900-01-01。这具有将每个日期向下舍入到每个季度的第一天的效果。

1 0 转换为 a 时datetime被视为1900-01-01.

于 2013-09-17T06:06:12.013 回答