Sum amount within a date range

I have 2 tables where I Need to sum up sales amount within a booking date range.
Below an example to help illustrate this task.
Table1:
CustomerID BookingDate (YYYY-MM-DD)
1 2014-04-29
1 2014-07-30
2 2014-03-31
2 2014-06-30
Table2:
CustomerID SalesDate (YYYY-MM-DD) Amount
1 2014-01-30 20
1 2014-02-25 30
1 2014-05-20 100
1 2014-07-30 200
1 2014-09-30 80
2 2014-03-20 50
Result:
CustomerID BookingDate (YYYY-MM-DD) Sum(Amount From Table2)
1 2014-04-29 50 -- SalesDate between 2014-01-01 and 2014-04-29
1 2014-07-30 300 -- SalesDate between 2014-04-30 and 2014-07-30
2 2014-03-31 50 -- SalesDate between 2014-01-01 and 2014-03-31
2 2014-06-30 0 -- SalesDate between 2014-04-01 and 2014-06-30

Please try this code:
declare @Table1 table
(CustomerID int,BookingDate date );
insert @Table1
values
( 1, '2014-04-29' ),
(1, '2014-07-30' ),
(2, '2014-03-31' ),
(2, '2014-06-30') ;
declare @Table2 table
(CustomerID int, SalesDate date, Amount int);
insert @Table2
values
(1,'2014-01-30',20) ,
(1,'2014-02-25',30) ,
(1,'2014-05-20',100) ,
(1,'2014-07-30',200) ,
(1,'2014-09-30',80) ,
(2,'2014-03-20',50) ;
with cte as
select
CustomerID,
BookingDate ,
row_number() over (partition by CustomerID order by BookingDate ) as rn
from @Table1 )
, cte2 as
select
T2.CustomerID ,
isnull(T1.BookingDate, '2014-01-01') as FromDate,
T2.BookingDate as ToDate
from cte as T1
right join cte as T2
on T1.rn = T2.rn - 1
and T1.CustomerID = T2.CustomerID
select
b.CustomerID ,
b.ToDate as BookingDate,
isnull(sum(a.Amount), 0) as [Sum(Amount From Table2)]
from @Table2 as a
right join cte2 as b
on a.CustomerID = b.CustomerID
and a.SalesDate > b.FromDate
and a.SalesDate <= b.ToDate
group by
b.CustomerID ,
b.ToDate;
T-SQL Articles
T-SQL e-book by TechNet Wiki Community
T-SQL blog

Similar Messages

  • Assign Month within a date range (by most days in a given month)

    I have a begin and end date, sample data as such
    select to_date('01-13-12','mm-dd-yy') from_dt,
    to_date('02-23-12','mm-dd-yy') to_dt
    from dual
    union all
    select to_date('03-15-2012','mm-dd-yy') from_dt,
    to_date('04-16-2012','mm-dd-yy') to_dt
    from dual
    union all
    select to_date('05-13-2012','mm-dd-yy') from_dt,
    to_date('07-23-2012','mm-dd-yy') to_dt
    from dual
    How do I assign a month by the most days in a month within that date range? Sometimes the date range might have the exact same amount of days in a month (like 3/15/2012 has 16 days and 4/16/2012 has 16 days). In this case, I want the earlier month (march).
    So from the sample data:
    01/13/2012, 02/23/2012, February
    03/15/2012, 04/16/2012, March
    05/13/2012, 07/23/2012, June
    Thanks
    Edited by: user4422426 on Mar 1, 2012 5:15 PM

    Hi,
    Here's one way:
    WITH     cntr          AS
         SELECT     LEVEL - 1     AS n
         FROM     (
                   SELECT      1 + MAX (to_dt - from_dt)     AS max_day_cnt
                   FROM     table_x
         CONNECT BY     LEVEL     <= max_day_cnt
    ,     got_r_num     AS
         SELECT     x.from_dt, x.to_dt
         ,     TRUNC (x.from_dt + c.n, 'MONTH')     AS month
         ,     count (*)                    AS cnt
         ,     ROW_NUMBER () OVER ( PARTITION BY  from_dt, to_dt
                             ORDER BY        COUNT (*)     DESC
                             ,             TRUNC (x.from_dt + c.n, 'MONTH')
                           )     AS r_num
         FROM       cntr     c
         JOIN       table_x  x  ON  c.n  <= x.to_dt - x.from_dt
         GROUP BY  x.from_dt, x.to_dt
         ,       TRUNC (x.from_dt + c.n, 'MONTH')
    SELECT     from_dt, to_dt
    ,     TO_CHAR (month, 'Mon YYYY')     AS mon
    ,     cnt
    FROM     got_r_num
    WHERE     r_num     = 1
    ;Thanks for posting code to create the same data. Please test your code before you post it: you got the order of arguments to TO_DATE reversed.

  • Conditional Sum... dynamic Date range MDX

    Hi
    i had question just now and got the right answer for it. That was great. However, I ran and the result was not right.
    It turned out I can not just sum up sales from the current date to the last date of sales but add one extra condition.
    I have three dimensions: Invoice Date, Licence Start Date, Licence End date. I need to add a condition saying only sales with licence start date is equal or early than current licence end date for the below query.
    I am looking at Filter function in MDX book right now. ahh It's been too long since I used the MDX last time. This is kinda urgent. Any help would be appreciated.
    I have added the condition as follows. It is not right because I got the same result as the first one. It should be less.
    And I think it's because the current member of licence start date for the expired month invoices are not applied right. 
    With member MEASURES.ActiveLicences as 
    sum ( 
    Filter(
    {[License Expiry Date].[FinancialYear].CurrentMember: null },
    ([Licence Start Date].[Financial_Year].CurrentMember <= [License Expiry Date].[FinancialYear].CurrentMember)
    [Measures].[No of Students]
    select {
    MEASURES.ActiveLicences,
    [Measures].[No of Students] } on columns, 
    [License Expiry Date].[FinancialYear].[YY-MMM].members on rows 
    from [Sales];
    from 
    With member MEASURES.ActiveLicences as 
    sum ( 
    {[License Expiry Date].[FinancialYear].CurrentMember: null },
    [Measures].[No of Students]
    select {
    MEASURES.ActiveLicences,
    [Measures].[No of Students] } on columns, 
    [License Expiry Date].[FinancialYear].[YY-MMM].members on rows 
    from [Sales];
    Kind regards

    Hi Sqlma,
    According to your description, you are going to sum the measure for the members with the dondition that licence start date is equal or early than current licence end date for the below query, right?
    In this case, you need filter out the members that licence start date is equal or early than current licence end date for the below query. And then sum the total measures using sum function. I have tested it on my local environment, here is a sample query
    for you reference.
    with set [aa]
    as
    filter
    ([Product].[Product Categories].members,
    [Measures].[Internet Sales Amount]>30000)
    member [measures].[b]
    as
    sum([aa],[Measures].[Internet Sales Amount])
    select {[Measures].[Internet Sales Amount],[measures].[b]} on 0,
    [aa] on 1
    from [Adventure Works]
    where [Date].[Calendar].[Calendar Year].&[2008]
    Regards,
    Charlie Liao
    TechNet Community Support

  • Getting last-day-of-week dates within certain date range

    Hi all,
    I have the following Challenge:
    I want to know the dates of the last day of all the weeks within a certain range of dates.
    For instance if my range would be 01-jun-2002 - 31-jun-2002
    then the returned days should be (lastday of the week is sunday):
    . 02-jun-2002
    . 09-jun-2002
    . 16-jun-2002
    . 23-jun-2002
    . 30-jun-2002
    I want to accomplish this by only using sql (no pl/sql) in a ora 8.0.x rdbms
    How would I do this? (if it's possible)
    Tia,
    Martin

    Christian's solution returns
    01-JUN-02
    08-JUN-02
    15-JUN-02
    22-JUN-02
    on my system. The first day of the week is dependent on NLS settings.
    SELECT MAX(realdate)
    FROM (
    SELECT TO_CHAR(TO_DATE('31-may-2002','dd-mon-yyyy') + ROWNUM,'IW') weekno,
           TO_DATE('31-may-2002','dd-mon-yyyy') + ROWNUM realdate
    FROM all_objects
    WHERE rownum <= TO_DATE('30-Jun-2002','dd-mon-yyyy') - TO_DATE('01-Jun-2002','dd-mon-yyyy')
    GROUP BY weeknoThe IW format model give ISO standard week numbers and a week always starts on Monday.

  • How can I sum values over a date range?

    I want to sum values (revenue) for a range of dates (i.e. for each month).  I'm trying to use  the MONTH function nested in SUMIF and keep getting an error message.  I want it to be SUMIF( MONTH (column of dates), cell with month, column with revenue) and it tells me "all ranges must be the same size".  It works if I create a separate column where I extract the month from each date and then compare that to a column with the number  of the month, but that is really annoying.

    You can use the sumif() function to compute the sum of revenues after the "End Date", the sum of revenues before some date and you can use the sum function to summ all revenue.  Then you can combine these into a single formula to get the answer by:
    sum between two dates is:
    sum("of all revenue") - sumif("before date") - sumif("after date"
    Cell B4 of the smaller table =SUM(Revenue)-SUMIF(Date, "<"&B1,Revenue)-SUMIF(Date, ">"&B2,Revenue)
    I highlighed cells to show before and after dates to highlight the sumif("after") and sumif("before")

  • Finding duplicates within a date range. SQL help please!!

    I have a table of records and I am trying to query the duplicate emails that appear within a given date range but cant figure it out.
    There records that it returns are not all duplicates withing the given date range.  HELP!!
    Here is my query.
    Thanks in advance.
    SELECT cybTrans.email, cybTrans.trans_id, cybTrans.product_number, cybTrans.*
    FROM cybTrans
    WHERE (((cybTrans.email) In (SELECT [email] FROM [cybTrans] As Tmp GROUP BY [email] HAVING Count(*)>1 ))
    AND ((cybTrans.product_number)='27')
    AND ((cybTrans.appsystemtime)>'03-01-2010')
    AND ((cybTrans.appsystemtime)<'03-05-2010')
    ORDER BY cybTrans.email;

    Yet another method...
    <cfset start_date = DateFormat('01/01/2007',
    'mm/dd/yyyy')>
    <cfset end_date = DateFormat('09/30/2009',
    'mm/dd/yyyy')>
    <cfset start_year = DatePart('yyyy', start_date)>
    <cfset end_year = DatePart('yyyy', end_date)>
    <cfset schoolyear_start = '09/01/'>
    <cfset schoolyear_end = '06/30/'>
    <cfset count = 0>
    <cfloop index="rec" from="#start_year#"
    to="#end_year#">
    <cfset tmp_start = DateFormat('#schoolyear_start##rec#',
    'mm/dd/yyyy')>
    <cfset tmp_end = DateFormat('#schoolyear_end##rec + 1#',
    'mm/dd/yyyy')>
    <cfif DateCompare(tmp_start,start_date) gt -1 and
    DateCompare(tmp_end, end_date) eq -1>
    <cfset count = count + 1>
    </cfif>
    </cfloop>
    <cfoutput>
    <br>There are #count# school year periods between
    #start_date# and #end_date#
    </cfoutput>

  • Obtaining data within a date range in XL Reporter

    Dear All,
    I'm currently working on BS in XL reporter.
    I was trying to extracting data in a date range, setting PER( Code >= @MthFrom Or Code <= @MthTo ) in report default tab.
    However, the result is shown as all data as of current date. E.g. Selection criteria: >=200808, <=200809, the result is shown as from Begining to 200810.
    Please kindly advise.
    Thank you.
    Regards,
    Julie
    Edited by: Julie Wan on Oct 1, 2008 1:10 PM

    Dear Gordon,
    Thank you for your reply.
    However my case is different to your given link.
    In my case, there is a result coming out, but not within the correct range i selected. It shows all instead.
    I tried to set the period range in report default tab,  in column tab of a expanding column, and in cell tab of an individual cell, but none have worked. E.g. PER( Code >= @MthFrom or Code <= @MthTo )
    Regards,
    Julie

  • Report for open invoice value against GR done within a date range

    Dear experts ,
    I need a report  between date ranges for which there is a GR done , but invoice is pending .
    Where can i get this ? 
    Regards
    Anis

    hi,
    You can  check few default PO reports wid proper paramater in it
    or
    Can check table EKBE
    or
    Check PO history in the PO doc
    Or
    Check the ME80FN
    Regards
    Priyanka.P

  • Ms Project 2013 report for resource name, tasks less than 100% complete within a date range I can set each time

    I have seen I can create a report for a resource name with a specified date range, and one that can show me for a resource name any incomplete tasks, but I want to do the following and cant work out how to state it in the report constructor:
    resource name equals - {I want to set a given resource in here}
    % complete is less than 100%
    start - date range is between [today -7 days] and [today +7 days]
    Please can someone show me how this is possible, I know it will be and it is me that has been defeated!!

    workspacedesign,
    Oops, my bad. I missed the point that the Name field for assignment rows will be the task name and that's not what you want. There is also a glitch in the date range filter. So, here's how to fix that.
    First, in the Resource Usage view, copy the Name field to Text1. Now select the resource line and do a fill down for all assignments under that resource. Do that for each resource. This could be automated with VBA, but for now, a manual setup should work
    fine.
    Second, instead of testing for the Name field in the filter, test for the Text1 field.
    Third, change the Finish test to be "less than or equal to".
    Now when you apply that filter, enter beginning date of your range and then the ending date of your range followed by the resource name. You should get the data you want.
    Unfortunately formulas in custom fields are not as flexible in Project as they are in Excel. For example, in Project a formula can only operate on data for that row. Further, even if you use the formula Today() +7 for your filter criteria, the first time
    the filter is used, Project will hard code today's date into the filter. The normal way around both of these shortcomings is to use VBA.
    Hope this helps.
    John

  • Calculate number of times a name appears within a date range.

    Hello,
    I am actually using the iPad version but I assume the formula will be the same. Say I have a date in column A and a list of names in column B. What would the formula be to calculate the number of times a specific name appears in a date range.
    Thank you

    If C2 = the minimum date of the range
    C3= the maximum date of the range
    and you are looking for John as the name
    =COUNTIFS($A,">="&C2,$A,"<="&C3,B,"john")
    which counts cells where A>=the min date and A<=the max date and B="john"

  • Date Range Within a Date Range

    I'm suffering from a mental block on this one and I'm hoping
    someone here can help. What I need to do is determine how many date
    ranges are between a broader date range. For example a school year
    runs from 9/1 to 6/30 or 180 work days. What I need to do is
    compute the number of 9/1 to 6/30 periods between say 1/1/2007 and
    9/30/2009. The result of this find is used in othere calculations
    in a rather complex report. Any help is appreciated.

    Yet another method...
    <cfset start_date = DateFormat('01/01/2007',
    'mm/dd/yyyy')>
    <cfset end_date = DateFormat('09/30/2009',
    'mm/dd/yyyy')>
    <cfset start_year = DatePart('yyyy', start_date)>
    <cfset end_year = DatePart('yyyy', end_date)>
    <cfset schoolyear_start = '09/01/'>
    <cfset schoolyear_end = '06/30/'>
    <cfset count = 0>
    <cfloop index="rec" from="#start_year#"
    to="#end_year#">
    <cfset tmp_start = DateFormat('#schoolyear_start##rec#',
    'mm/dd/yyyy')>
    <cfset tmp_end = DateFormat('#schoolyear_end##rec + 1#',
    'mm/dd/yyyy')>
    <cfif DateCompare(tmp_start,start_date) gt -1 and
    DateCompare(tmp_end, end_date) eq -1>
    <cfset count = count + 1>
    </cfif>
    </cfloop>
    <cfoutput>
    <br>There are #count# school year periods between
    #start_date# and #end_date#
    </cfoutput>

  • Populate dates within the date range columns in a table

    Hi ,
    I have a Students table with StudentID, StartDate and EndDate. For one of the requirements, I need to populate all the dates within and includeing the StartDate and EndDate for all the students. Please find the DDL for the source table samples and also below
    samples of Source table columns and how the output should be.
    create table #Students (ID int,startdate date,Enddate date)
    insert into #Students values (1000, '2014-01-01',
    '2014-01-10')
    insert into #Students values (1000, '2014-02-22',
    '2014-02-28')
    insert into #Students values (1001, '2013-07-01',
    '2013-07-12')
    insert into #Students values (1001, '2013-08-01',
    '2013-08-03')
    insert into #Students values (1001, '2014-04-01',
    '2014-04-05')
    --select * from #Students order by id,startdate
    --drop table #students
    Thanks in advance  for your help!

    Hi vskindia,
    A recursive way to achieve the expected output.
    create table #Students (ID int,startdate date,Enddate date)
    insert into #Students values (1000, '2014-01-01',
    '2014-01-10')
    insert into #Students values (1000, '2014-02-22',
    '2014-02-28')
    insert into #Students values (1001, '2013-07-01',
    '2013-07-12')
    insert into #Students values (1001, '2013-08-01',
    '2013-08-03')
    insert into #Students values (1001, '2014-04-01',
    '2014-04-05')
    ;WITH cte AS
    SELECT ID,startdate,Enddate FROM #Students
    UNION ALL
    SELECT ID,DATEADD(DAY,1,startdate) AS startdate,Enddate FROM cte
    WHERE startdate<Enddate
    SELECT id,startdate FROM CTE ORDER BY ID,startdate
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • Average for Unit Price within a date range????

    Howdy BI Gurus,
    We're on BI 7.0.
    The client has the following report that I neeed to create in BI:
    It's Determines the Average Costs for Raw Material Every Quarter:
    <b>Item #  |   Receipt Date|   Qty      |    Unit Cost  |   Extended Cost  |   Vendor</b>
    200TU      | 01/23/07        | 47,349   |      .9950      |   47,112.26         |      XYZ
    200TU      | 02/19/07        | 48,796   |      .9870      |   48,552.02         |      XYZ
    200TU      | 04/16/07        | 43,978   |      .9340      |   43,758.11         |      XYZ
    Total Sum  For Qty =  140,123
    Total Sum For Extended Cost = 139,422.39      
    Average  For Unit Cost =   .9720
    1. How do you calculate the <b>Average</b> for the <b>Unit Cost</b>?
    2. How do display the Total Sum ONLY for the <b>Qty</b> &&<b> Extended Cost</b>?
    I tried the following document:
    <b>"How to...Count the Occurances of a Characteristic"</b>
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/7e58e690-0201-0010-fd85-a2f29a41c7af
    ...that was posted on another forum that shows step by step how to create a Counter infoobject and update the transfer rules with a Constant "1" and after creating a CKF in Query Designer and setting up the Exception Aggregation for "Average of All Values" for Ref. Characteristic "Material" to get the average...Unfortunately, it didn't work for me as I just get $0.0. 
    I'm thinking maybe the directions were for the old BW version.
    Any help would be greatly appreciated.
    Best Regards,
    Osman

    This is what I get now when I do an Exception Aggregation on Ref. Char - Material...Look at the last Column titled "Average Unit Price"
    Calendar Day     Material     Individual price in invoice     Invoiced quantity     Extended Cost     Average Unit Price
    10/9/2007     17887          $ 14.00 /EA               7,128 EA          $ 99,792.00     $ 14.00 /EA
    10/22/2007     53093          $ 318.00 /EA               1,920 EA          $ 610,560.00     $ 318.00 /EA
    10/8/2007     4750MT          $ 0.51 /LB               252,000 LB          $ 128,088.00     $ 0.51 /LB
    10/9/2007     4750MT          $ 0.51 /LB               252,000 LB          $ 127,638.00     $ 0.51 /LB
    10/17/2007     G202          $ 59.40 /EA               6 EA               $ 356.40     $ 59.40 /EA
    What I want is grup by Material:
    Calendar Day     Material     Individual price in invoice     Invoiced quantity     Extended Cost     
    10/9/2007     17887          $ 14.00 /EA               7,128 EA          $ 99,792.00     
    Average Individual price in invoice = $14 (Since there is only 1)
    10/22/2007     53093          $ 318.00 /EA               1,920 EA          $ 610,560.00     
    Average Individual price in invoice = $318.00 (Since there is only 1)
    1/8/2007     4750MT          $ 0.51 /LB               252,000 LB          $ 128,520.00     
    2/9/2007     4750MT          $ 0.32 /LB               252,000 LB          $  80,640.00     
    3/10/2007     4750MT          $ 0.24 /LB               252,000 LB          $  60,480.00     
    4/25/2007     4750MT          $ 0.65 /LB               252,000 LB          $ 163,800.00     
    Average Individual price in invoice = (($0.51 + $0.32 + $0.24 + $0.65) / 4) = $0.43
    10/17/2007     G202          $ 59.40 /EA               6 EA               $ 356.40     
    Average Individual price in invoice = $59.40 (Since there is only 1)
    Hi Kartikey,
    I'll try your method tommorrow morning...thank you for your help so far.
    I really appreciate it
    Best Regards,
    Osman
    Message was edited by:
            Osman Baig

  • Tax not calculating in MIRO within a date range.

    Hi Experts ,
    We have created a tax code and assign its values in condition types under two separate Key Combination.
    1) Tax Classification : 4% ( Non Validity) , in access sequence exclusive indicator is set aganst it.
    2)  Tax Code : 4% (Valdity - Sept - till 9999), Exclusive indicator is not set against it.
    Issue is that when i create a PO ( at any date) system is picking up the taxes.
    Nom at the time of MIRO , if i post the MIRO before sept. system is allowing me to do so and calculate taxes correctly.
    But when i change the date to Sept the system does not calculate taxes.
    Even though the Tax Classification has more priority in access sequence compared to tax code , i am failed to understand why system is not calculating taxes.
    I have tried deleting conditions in tax code key combinations but still system is not calculating taxes in MIRO,
    Pls guide.
    Regards
    Honey

    Hi Ramesh ,
    i have done the same . Maintained he condition record via FV11. but system is not calculating tax for sept. month in MIRO.
    In PO tax calculation is perfect but in MIRO it is not calculating tax.( ticked calculate tax option also).

  • Displaying different sums in the same row based on date ranges

    Say I had a table like this
    DECLARE @t1 TABLE (RowId INT PRIMARY KEY IDENTITY(1,1), BusinessType VARCHAR(100), SalesPerson VARCHAR(100), Category VARCHAR(100), OrderAmount DECIMAL(10,2), OrderDate DATETIME )
    Now I want to get a result that is grouped first by BusinessType, then SalesPerson and include derived columns that are sums based  on different date ranges.
    Month-to-date = from the start of the current month to today
    Month-to-date previous year = from the start of the current month to today 1 year ago
    DECLARE @today DATETIME
    DECLARE @today_prev_year DATETIME
    DECLARE @year_start DATETIME
    DECLARE @year_prev_start DATETIME
    DECLARE @month_start DATETIME
    DECLARE @month_prev_start DATETIME
    SET @today = GETDATE();
    SET @today_prev_year = DATEADD(YEAR,-1,@today)
    SET @year_start = CAST('01/01/' + CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR(10)) AS DATETIME);
    SET @year_prev_start = DATEADD(YEAR,-1,@year_start)
    SET @month_start = DATEADD(month, DATEDIFF(month, 0, @today), 0); --gets the first of the current month
    SET @month_prev_start = DATEADD(YEAR,-1,@month_start); --gets the first of the current month
    SELECT t.BusinessType,t.SalesPerson,t.Category
    SUM(CASE WHEN o.OrderDate > @month_start AND ac.DocumentDate < @today THEN o.OrderAmount ELSE 0 END) AS MTDActualAmount
    SUM(CASE WHEN o.OrderDate > @month_prev_start AND ac.DocumentDate < @today_prev_year THEN o.OrderAmount ELSE 0 END) AS MTDPrevActualAmount
    FROM @t1 t
    Hope this is clear as to what Im trying to do.  Im ultimately going to pull this into an SSRS report, so im wondering if I can do this different SUM values in the report and handle the grouping there.
    Thoughts?

    Based on your example (with a group by added) it should work.
    However, if you incorperated a calendar table (http://social.technet.microsoft.com/wiki/contents/articles/29260.tsql-calendar-functions-and-tables.aspx)
    you could lose all those manually set parameters:
    DECLARE @t1 TABLE (RowId INT PRIMARY KEY IDENTITY(1,1), BusinessType VARCHAR(100), SalesPerson VARCHAR(100), Category VARCHAR(100), OrderAmount DECIMAL(10,2), OrderDate DATETIME, DocumentDate DATETIME)
    INSERT INTO @t1 (BusinessType, SalesPerson, Category, OrderAmount, OrderDate, DocumentDate) VALUES
    ('A','Joe','CatA',10,'2015-01-01','2015-01-01'),('A','Joe','CatB',10,'2015-01-02','2015-01-01'),('A','Joe','CatA',30,'2015-01-03','2015-01-04'),('A','Joe','CatB',40,'2015-01-04','2015-01-01'),('A','Joe','CatA',100,'2015-02-01','2015-02-01'),
    ('A','Joe','CatB',100,'2015-02-02','2015-02-01'),('A','Joe','CatA',300,'2015-02-03','2015-02-04'),('A','Joe','CatB',400,'2015-02-04','2015-02-01'),('A','Bob','CatA',1,'2015-01-01','2015-01-01'),('A','Bob','CatB',1,'2015-01-02','2015-01-01'),
    ('A','Bob','CatA',3,'2015-01-03','2015-01-04'),('A','Bob','CatB',4,'2015-01-04','2015-01-01'),('A','Bob','CatA',10,'2015-02-01','2015-02-01'),('A','Bob','CatB',10,'2015-02-02','2015-02-01'),('A','Bob','CatA',30,'2015-02-03','2015-02-04'),
    ('A','Bob','CatB',40,'2015-02-04','2015-02-01'),('B','Joe','CatA',10,'2015-01-01','2015-01-01'),('B','Joe','CatB',10,'2015-01-02','2015-01-01'),('B','Joe','CatB',40,'2015-01-04','2015-01-01'),
    ('B','Joe','CatA',100,'2015-02-01','2015-02-01'),('B','Joe','CatB',100,'2015-02-02','2015-02-01'),('B','Joe','CatA',300,'2015-02-03','2015-02-04')
    SELECT t.BusinessType,t.SalesPerson,t.Category,
    SUM(CASE WHEN OrderDate >= monthStart AND DocumentDate < today THEN OrderAmount ELSE 0 END) AS MTDActualAmount,
    SUM(CASE WHEN OrderDate BETWEEN prevMonthStart AND prevMonthENd AND DocumentDate >= yearStart THEN OrderAmount ELSE 0 END) AS MTDPrevActualAmount
    FROM @t1 t
    INNER JOIN calendar c
    ON today = CAST(CURRENT_TIMESTAMP AS DATE)
    Group by t.BusinessType,t.SalesPerson,t.Category

Maybe you are looking for

  • Some service missing in PI 7.31

    Hi Experts, Urgent!! I'm checking readiness of SAP PI 7.31 dual stack and following SAP note : 817920. When run transaction SICF for testing the HTTP services on the Integration Server, some service is missing, like esf_secure,pm. Please suggest what

  • BPEL Process getting halted even after expired.

    I have a BPEL process which call a certain human task. human task expires in some x amount of time. so after expiry the Escalation & Renew Policy should kick in. but the task is still visible to the same user and the process is still waiting for the

  • Not communicating with scanning device

    I am running windows xp home edition sp2 with an hp office jet 5600xi all in one printer. Just switched to google chrome and I get the" no communication with the device error message" when trying to scan but can still print and copy.  tried all the s

  • How to add addition products to existing 11i installation

    Can we do the below steps to add aditional products 1) OAM -> Site Map --> License Manager Home --> License Products > License Component Application --> select additional products Complete the registration process in OAM 2) run autoconfig 3) generate

  • On the latest operating system where do I find my iPhoto library

    Where do I find my iPhoto library in the latest operating system?