我在SQL Server中有表:
Table (Id, Year, Value)
和这样的数据:
Id | Year | Value
---+------+------
1 | 1993 | 5
2 | 1994 | 1
3 | 1995 | 2
4 | 1996 | 15
5 | 1997 | 8
6 | 1998 | 3
7 | 1999 | 1
8 | 2000 | 5
我每四年需要一笔钱,例如
Years | SUM (Value)
----------+-------------
1993-1996 | 23
1997-2000 | 17
我该怎么做?
答案 0 :(得分:7)
您可以使用简单的算术:
select min(year), max(year), sum(value)
from t
group by (year - 1) / 4
order by min(year);
注意:
order by
,因此结果符合您的预期顺序。答案 1 :(得分:0)
您可以使用group by
子句来获取所需的特定分组。
declare @StartYear int = 1993;
declare @YearsPerGroup int = 4;
select
case
when min([year]) = max([year]) then cast(min([year]) as varchar(10))
else cast(min([year]) as varchar(10)) + '-' + cast(max([year]) as varchar(10))
end as [Name],
min([year]) as [Start Year],
max([year]) as [End Year],
sum(Value) as [Sum (Value)]
from T
group by
([year] - @StartYear) - ([year] - @StartYear) % @YearsPerGroup