Solved

Producing Monthly Totals with SQL

Posted on 2011-09-15
11
242 Views
Last Modified: 2012-05-12
I've never tried this with SQL, but I'm sure it's possible.
I have data prepared nicely with the following self-explanatory fields:

ID, DAILY_AMOUNT, TERM_START, TERM_END

I want to turn this into a report that yields total DAILY_AMOUNT where the selection criteria specify a start and end date.
So, for example, this could be used to answer the question, "How much did I spend on widgets in July of 2010?".
So If I spent $5 every day on widgets from, say, 2010/6/12 to 2010/7/5, the answer would be $25 ($5 x 5 Days in July).

What's the smart way to do this?

Mike
0
Comment
Question by:shacho
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
  • +1
11 Comments
 
LVL 25

Expert Comment

by:jogos
ID: 36547447
select year(TERM_END),month(TERM_END), sum(DAILY_AMOUNT)
from tabelname
where TERM_END between   .. and ..
group by year(TERM_END),month(TERM_END)
0
 

Author Comment

by:shacho
ID: 36547454
That would work if I had individual records for each day.  I don't I only have the "daily amount".  So I need to calculate how many days the expense term and the extraction term have in common.  If I have that number, I can multiply by the daily amount to get the sum.
0
 
LVL 4

Expert Comment

by:AnuTiji
ID: 36547457
Hi

Please find the TSQL statement below:

DECLARE @TERM_STARTDATE datetime
DECLARE @TERM_ENDDATE datetime

SET @TERM_STARTDATE  = '05/05/2010' (Input: Start date of the period)
SET @TERM_ENDDATE ='05/08/2010' (Input: End date of the period)

SELECT sum(ISNULL(DAILY_AMOUNT,0) * DATEDIFF(day,TERM_START, TERM_END)) as amount FROM table_name WHERE DATEDIFF(day,@TERM_STARTDATE, TERM_START) >=0  AND DATEDIFF(day,@TERM_ENDDATE, TERM_END) <=0  
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:shacho
ID: 36547574
I can't quite see how that would work.  There are several scenarios that need to be considered, e.g. ranges that don't overlap, partially overlap, are sub or super sets of each other, etc.  This is how I do it (in Access with VBA) right now.  This may clarify what the actual data look like.  This is a fine solution, but SQL would be much faster.

Public Function OverLap(TermStart As Date, TermEnd As Date, RangeStart As Date, RangeEnd As Date) As Integer
    Dim StartDate As Date, EndDate As Date
    OverLap = 0
    If TermEnd < RangeStart Then Exit Function
    If TermStart > RangeEnd Then Exit Function
    If RangeEnd < TermEnd Then EndDate = RangeEnd Else EndDate = TermEnd
    If RangeStart > TermStart Then StartDate = RangeStart Else StartDate = TermStart
    OverLap = EndDate - StartDate + 1
End Function
0
 
LVL 4

Expert Comment

by:AnuTiji
ID: 36547623
hi

I believe the above conditions are satisfied by sql query pasted below. Can you test the sql query for a date range?

DECLARE @TERM_STARTDATE datetime
DECLARE @TERM_ENDDATE datetime

SET @TERM_STARTDATE  = '05/05/2010' (Input: Start date of the period)
SET @TERM_ENDDATE ='05/08/2010' (Input: End date of the period)

SELECT sum(ISNULL(DAILY_AMOUNT,0) * DATEDIFF(day,TERM_START, TERM_END)) as amount FROM table_name WHERE DATEDIFF(day,@TERM_STARTDATE, TERM_START) >=0  AND DATEDIFF(day,@TERM_ENDDATE, TERM_END) <=0  
0
 
LVL 22

Accepted Solution

by:
Thomasian earned 500 total points
ID: 36547694

SELECT SUM(DAILY_AMOUNT
           * DATEDIFF(day, CASE WHEN TERM_START>@RangeStart
                                THEN TERM_START
                                ELSE @RangeStart
                            END
                          , CASE WHEN TERM_END>@RangeEnd
                                THEN TERM_END
                                ELSE @RangeEnd
                            END
                     )
          ) As [Amount]
FROM tablename
WHERE ID=@ID
      AND TERM_START<=@RangeEnd
      AND TERM_END>=@RangeStart

Open in new window

0
 

Author Comment

by:shacho
ID: 36547718
There we go.  Essentially an SQL version of my VB function.  Nifty.
0
 
LVL 25

Expert Comment

by:jogos
ID: 36547767
In calculation that must be datediff + 1
with case you can select the apropriate date
DECLARE @TERM_STARTDATE datetime
DECLARE @TERM_ENDDATE datetime

SET @TERM_STARTDATE  = '05/05/2010' -- (Input: Start date of the period)
SET @TERM_ENDDATE ='05/08/2010' --(Input: End date of the period)

select year(TERM_END) as y,month(TERM_END) as m
, sum(ISNULL(DAILY_AMOUNT,0) 
* (DATEDIFF(day,
  (case when TERM_START > @TERM_STARTDATE then TERM_START else @TERM_STARTDATE end) 
  , (case when TERM_END < @TERM_ENDDATE then TERM_END else @TERM_ENDDATE end))
  +1) as amount 
from tablename
where TERM_END >= @TERM_STARTDATE 
 and TERM_START <= @TERM_ENDDATE 
group by year(TERM_END),month(TERM_END)

Open in new window

0
 

Author Comment

by:shacho
ID: 36547770
indeed
0
 
LVL 25

Expert Comment

by:jogos
ID: 36547775
sorry for duplicate, aswer was waiting for submit when I got a long call :)
0
 

Author Comment

by:shacho
ID: 36547783
np - thanks for commenting.
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Did you know that more than 4 billion data records have been recorded as lost or stolen since 2013? It was a staggering number brought to our attention during last week’s ManageEngine webinar, where attendees received a comprehensive look at the ma…
The Windows Phone Theme Colours is a tight, powerful, and well balanced palette. This tiny Access application makes it a snap to select and pick a value. And it doubles as an intro to implementing WithEvents, one of Access' hidden gems.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
With Microsoft Access, learn how to start a database in different ways and produce different start-up actions allowing you to use a single database to perform multiple tasks. Specify a start-up form through options: Specify an Autoexec macro: Us…

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question