Solved

Producing Monthly Totals with SQL

Posted on 2011-09-15
11
243 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
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 

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

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

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

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.
In part one, we reviewed the prerequisites required for installing SQL Server vNext. In this part we will explore how to install Microsoft's SQL Server on Ubuntu 16.04.
In Microsoft Access, learn the trick to repeating sub-report headings at the top of each page. The problem with sub-reports and headings: Add a dummy group to the sub report using the expression =1: Set the “Repeat Section” property of the dummy…
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

632 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