Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Created December 15, 2013 14:04
Show Gist options
  • Select an option

  • Save ichiroku11/7973427 to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/7973427 to your computer and use it in GitHub Desktop.
over句を使って累計
if object_id(N'tempdb..#Sale') is not null
drop table #Sale;
select *
into #Sale
from (values
('2013/12/09', N'ねぎま', 100),
('2013/12/10', N'ねぎま', 200),
('2013/12/11', N'純けい', 100),
('2013/12/12', N'純けい', 300),
('2013/12/14', N'ねぎま', 400),
('2013/12/14', N'純けい', 200),
('2013/12/15', N'ねぎま', 100)) as Src(Date, Name, Value);
select Name, Date, Value,
sum(Value) over(partition by Name order by Date) as Accumulated
from #Sale
order by Name, Date;
/*
Name Date Value Accumulated
------- ---------- ----------- -----------
ねぎま 2013/12/09 100 100
ねぎま 2013/12/10 200 300
ねぎま 2013/12/14 400 700
ねぎま 2013/12/15 100 800
純けい 2013/12/11 100 100
純けい 2013/12/12 300 400
純けい 2013/12/14 200 600
*/
select Date, Name, Value,
sum(Value) over(order by Date) as Accumulated
from #Sale
order by Date;
/*
Date Name Value Accumulated
---------- ------- ----------- -----------
2013/12/09 ねぎま 100 100
2013/12/10 ねぎま 200 300
2013/12/11 純けい 100 400
2013/12/12 純けい 300 700
2013/12/14 ねぎま 400 1300
2013/12/14 純けい 200 1300
2013/12/15 ねぎま 100 1400
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment