Solved

Producing Monthly Totals with SQL

Posted on 2011-09-15
11
241 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
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 

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

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

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

As tax season makes its return, so does the increase in cyber crime and tax refund phishing that comes with it
Access developers frequently have requirements to interact with Excel (import from or output to) in their applications.  You might be able to accomplish this with the TransferSpreadsheet and OutputTo methods, but in this series of articles I will di…
Basics of query design. Shows you how to construct a simple query by adding tables, perform joins, defining output columns, perform sorting, and apply criteria.
With Microsoft Access, learn how to specify relationships between tables and set various options on the relationship. Add the tables: Create the relationship: Decide if you’re going to set referential integrity: Decide if you want cascade upda…

735 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