我对sql很新,我有一个小问题。所以我有这张桌子" main.person"它具有值' Balance'和' birthYear'在里面。 现在我想生成统计数据,显示3个不同的birthYear组的总余额。例如,从最小出生年(最老)到1/3的范围。然后从范围的1/3到2/3。然后从2/3到最年轻(最大值)
我一直试图用ntile来做这件事,但它并不能很好地工作,因为它没有很好地将范围分成3组,因为例如1958年是同组也是第2组。任何帮助都将不胜感激。感谢。
这是我的代码:
create or alter procedure main.generateStatistics
as
begin
declare @bracket table(
balance numeric(9,2) not null,
bracket nvarchar(20))
insert into @bracket([balance],[bracket])
SELECT balance, NTILE(3) OVER(ORDER BY birthYear) from main.person p) as z
set @group1 = (select sum(balance) from @bracket
where bracket = 1)
set @group2 = (select sum(balance) from @bracket
where bracket = 2)
set @group3 = (select sum(balance) from @bracket
where bracket = 3)
insert into main.[stats](dateCollected,totalPeople,bracket1,bracket2,bracket3)
values(SYSDATETIMEOFFSET(),(select count(*) from main.person), @group1, @group2,@group3)
end;
我希望我的分组如何
的示例set @group1=(
select sum(balance) from main.person p
where birthYear <= 1959)
set @group2=(
select sum(balance) from main.person p
where birthYear >= 1960 and birthYear <= 1979)
set @group3=(
select sum(balance) from main.person p
where birthYear >= 1980)
[