SQL Puzzler

Welcome to a new feature, SQL Puzzlers! Hope you enjoy them. Follow the link above to see all that we have. 

Here is a puzzler for the SQL types in the crowd

Given this dataset:

 

How would you code a running total?

 

I've gotten you started, here is the code that produces the first window, all you have to do is code the RunningTotal column. 

declare @t table (RowID int identity, Docdate date, Sales numeric(19,2))
insert into @t (docdate, Sales) values ('1/1/2019',100)
insert into @t (docdate, Sales) values ('1/2/2019',200)
insert into @t (docdate, Sales) values ('1/3/2019',300)
insert into @t (docdate, Sales) values ('1/4/2019',400)
insert into @t (docdate, Sales) values ('1/5/2019',500)
 
select *
    from @t
    order by docdate

The answer is below, peek at your own peril. 

 

 

Related Articles

... and you 'll find more on the SQL (General) Menu

 

Spoiler alert!

select Rowid,
        Docdate,
        Sales,
        sum(Sales) over (order by docdate ROWS UNBOUNDED preceding) as RunningTotal
    from @t
    order by docdate


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences