我有一个问题,我想通过日期合并我的表格数据,所有信息都在给定的表格中提供
如果聚合= Quaterly
我的表
表格-1
Amount | Date | Aggregation
100 | 2013-01-01 | Quaterly
100 | 2013-02-01 | Quaterly
100 | 2013-03-01 | Quaterly
200 | 2013-04-01 | Quaterly
200 | 2013-05-01 | Quaterly
200 | 2013-06-01 | Quaterly
300 | 2013-07-01 | Quaterly
300 | 2013-07-01 | Quaterly
300 | 2013-09-01 | Quaterly
400 | 2013-10-01 | Quaterly
400 | 2013-11-01 | Quaterly
400 | 2013-12-01 | Quaterly
我想要这样的结果
Amount | Date | Aggregation
300 | 2013-03-01 | Quaterly
600 | 2013-06-01 | Quaterly
900 | 2013-09-01 | Quaterly
1200 | 2013-12-01 | Quaterly
答案 0 :(得分:0)
点击这里是财政季度+总和
;With Totals as (
SELECT SUM(Amount) as Total,
DATEADD(quarter,DATEDIFF(quarter,0,date),0) as RoundQuarter
FROM dbo.MyData AS om
GROUP BY
DATEADD(quarter,DATEDIFF(quarter,0,date),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
答案 1 :(得分:0)
如果您的宿舍只能通过日历(非财政)年度进行更改,您可以试试这个:
SELECT amount,
Cast(Cast(mydate / 10 * 10000 + ( mydate%10 ) * 300 + 1 AS VARCHAR) AS
DATE) AS
MyDate,
aggregation
FROM (SELECT Sum(amount) AS Amount,
Datepart(yyyy, mydate) * 10 + Datepart(qq, mydate) AS MyDate,
Max(aggregation) AS Aggregation
FROM table1
GROUP BY Datepart(yyyy, mydate) * 10 + Datepart(qq, mydate)) a
ORDER BY 2
首次计算子查询中的所有聚合(或使用WITH-construction),就像在另一个答案中一样。日期是用年份密钥计算的,如果你不需要多年的结果,可以删除'datepart(yyyy,MyDate)* 10 +'。之后,您将季度数与特定年份合并。请不要将“MyDate / 10 * 10000”部分替换为“MyDate * 1000”,我们需要删除不必要的数字以生成正确的日期格式。