Difference between SUM values in adjoining rows

Hi I've written following query:
DECLARE @Decision_Group nvarchar(10) = 'All',
@Entry_Month INT = 09,
@In_Use CHAR(1) = 'Y',
@Scheme nvarchar(05) = 'UGS',
@Subject_Area nvarchar(10) = 'ART',
@Location nvarchar(10) = 'UOB',
@Home_Overseas nvarchar(05) = 'H'
SELECT SUM(a.CONVERSION_EARLY) AS Early, SUM(a.CONVERSION_MIDDLE) AS Middle, SUM(a.CONVERSION_CLEARING) AS Clearing, a.AcademicYear
FROM
SELECT
srs_cap.cap_ayrc AS AcademicYear
,CONVERSION_EARLY =
CASE
WHEN (srs_cap.cap_crtd < cast('02/10/' + left(srs_cap.cap_ayrc,4) AS dateTime)) THEN 1
END
,CONVERSION_MIDDLE =
CASE
WHEN (
srs_cap.cap_crtd < cast('08/01/' + left(srs_cap.cap_ayrc,4) AS dateTime) AND
srs_cap.cap_crtd >= cast('02/10/' + left(srs_cap.cap_ayrc,4) AS dateTime)) THEN 1
END
,CONVERSION_CLEARING =
CASE WHEN (srs_cap.cap_crtd >= cast('08/01/' + left(srs_cap.cap_ayrc,4) AS dateTime)) THEN 1
END
FROM srs_cap
LEFT JOIN srs_mcr ON srs_cap.cap_mcrc = srs_mcr.mcr_code
LEFT JOIN srs_dsc ON srs_cap.cap_dscc = srs_dsc.dsc_code
LEFT JOIN srs_mth ON srs_cap.cap_mthc = srs_mth.mth_code
LEFT JOIN ins_lca ON srs_cap.cap_cgpc = ins_lca.lca_code
LEFT JOIN men_xon ON men_xon.xon_oldv = srs_cap.cap_dptc
LEFT JOIN ins_dpt ON srs_cap.cap_dptc=ins_dpt.dpt_code
LEFT JOIN srs_sce ON srs_cap.cap_scjc = srs_sce.sce_scjc
AND srs_cap.cap_ayrc = srs_sce.sce_ayrc
WHERE cap_ayrc BETWEEN dbo.[GetAcademicYear-2] (getdate()) AND dbo.getnextacademicyear(getdate())
AND (@Decision_Group='All' OR (@Decision_Group<>'A' AND RIGHT(srs_cap.cap_dscc,1) IN (left(@Decision_Group,1)) ))
AND cap_mthc IN (@Entry_Month)
AND srs_mcr.mcr_iuse IN (@In_Use)
AND srs_cap.cap_schc IN (@Scheme)
AND srs_cap.cap_dptc IN (@Subject_Area)
AND srs_cap.cap_cgpc IN (@Location)
AND srs_cap.cap_apcc IN (@Home_Overseas)
AND (men_xon.xon_tabl='Academic Group' or men_xon.xon_tabl IS NULL)
GROUP BY
srs_cap.cap_ayrc,
srs_cap.cap_crtd
AS a
GROUP BY
AcademicYear
This returns following data.
    Early
    Middle
  Clearing
AcademicYear
79
58
  27    
   2012/13
69
58
37
   2013/14
75
55
30
   2014/15
67
6
      NULL
   2015/16
Is there a simple way using windows functions to get the difference between Early 2012/13 and Early 2013/14, then Middle 2012/13 and Middle 2013/14 etc?
Cheers, AndySugs

Please follow basic Netiquette and post the DDL we need to answer t His. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You are not even close. 
You should follow ISO-8601 rules for displaying temporal data. We need to know the data types, keys and constraints on the table. You failed again and did it in the worst way! Is your '08/01/'  supposed to be “yyyy-08-01” or “yyyy-01-08” ? Who knows? This
is why ANSI/ISO Standard SQL allows only the “yyyy-mm-dd” display format. 
Avoid dialect in favor of ANSI/ISO Standard SQL. 
Why did you treat temporal data like 1960's COBOL strings? And then you picked the worst possible display format! 
Why do you write with assembly language flags? 
Why did you write more left outer joins in ONE query than I have written in the last three years? Your DDL (which you did not post) would have to be total mess. 
Why do you think that table names of less than 8 characters are maintainable? I am old and remember when file names had to be less than 8 characters but that was in the 1970's on magnetic tape file systems. 
Why do you think that “cap_ayrc” is better than the ISO-1179 compliant “academic_year” that you had to alias it to? In RDBMS, a data element has one and only one name. This name does not contain meta data. The general syntax is “<attribute>_<attribute
property>”
The old Sybase/UNIX  getdate() should be CURRENT_TIMESTAMP today. 
Competent SQL programmers do not use UDF. They do not port, the overhead is too great and they cannot be optimized. But VB, COBOL and programmers in other procedural languages use them to avoid learning declarative programming. This means your silly [Get_Academicyear-2]
() and Get_Next_Academicyear() would be in a report period look-up table. SQL is a data base language so we use tables instead of computations. 
Why did you write code like:
 S.cap_schc IN (@scheme_name) ?
The IN() predicate implies that you are passing a list. But First Normal Form (1NF) uses scalars. That would be sooo wrong! 
My guess is that when you fix the schema, this query would look more like this skeleton: 
SELECT A.academic-year,
            SUM (CASE  WHEN (A.foobar_date < R.something_start_date)  
                     THEN 1 ELSE 0 END)) AS early_conversion_cnt, 
            SUM (CASE  WHEN (A.foobar_date BETWEEN R.something_start_date
                         AND R.something_end_date)  AS middle_conversion_date
                     THEN 1 ELSE 0 END)) AS early_conversion_cnt, 
            SUM (CASE  WHEN (A.foobar_date >  R.something_end_date)  
                     THEN 1 ELSE 0 END)) AS AS clearing_conversion_cnt
FROM  Report_Periods AS R,  .. AS A
WHERE  .. ;
Do you want to follow the forum rules and try again with DDL and specs? Having taught SQL and having other credentials, I would say that you are 3-5 years from being a productive SQL programmer. 
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • DIFFERENCE BETWEEN SUM AND COUNT IN SQL

    DIFFERENCE BETWEEN SUM AND COUNT IN SQL
    WHAT IS THE DIFFERENCE VERIFY IN DETAIL/

    21031980, I suggest you upgrade your computer sothat you can access google.
    lol.
    wtfpwnd.Google is also helpful for understanding the strange
    acronyms that show up around here lately (yes, I did
    find and understand this one). :-)Haha, sorry!
    It's the inner-gamer in me rearing its ugly head...
    :-)

  • I have bought an iPhone 4S in Brazil and I would like to know if I can replace my old iPhone for a new one (iPhone 5S), at some Apple Store in USA, if I pay just the difference between both values.

    I have bought an iPhone 4S in Brazil and I would like to know if I can replace my old iPhone for a new one (iPhone 5S), at some Apple Store in USA, if I pay just the difference between both values.

    You're welcome.
    I would advise against that for the reasons I provided.
    Could I have my iPad 2 for the new one paying the difference between their values?
    No. Sell the existing yourself and use the proceeds to purchase a new iPad.

  • Difference between copy value and use one as many

    hi
    what  is the difference between copy value and use one as many?
    thanks

    [http://help.sap.com/saphelp_nw2004s/helpdata/en/26/d22366565be0449d7b3cc26b1bab10/content.htm]
    [http://help.sap.com/saphelp_nw2004s/helpdata/en/ef/df564b6aa24fc9ab0d685460747de5/content.htm]
    Much better understanding of UseOneAsMany: [http://help.sap.com/saphelp_nw2004s/helpdata/en/38/85b142fa26c811e10000000a1550b0/content.htm]
    Edited by: Praveen Gujjeti on Feb 18, 2010 11:42 AM

  • Difference between a value table and a check table?

    What is the difference between a value table and a check table?

    Value Table
    This is maintained at Domain Level.
    When ever you create a domain , you can entered allowed values.   For example  you go to Domain   SHKZG - Debit/credit indicator.  Here only allowed values is H or S.
    When ever you use this Domain, the system will forces you to enter only these values.
    This is a sort of master check . To be maintained as a customization object. This mean that if you want to enter values to this table you have to create a development request & transport the same.
    Check table
    For example you have Employee master table & Employee Transaction table.
    When ever an employee Transacts we need to check whether that employee exists , so we can refer to the employee master table.
    This is nothing but a Parent & Child relationship .  Here data can be maintained at client level , no development involved.
    As per DBMS what we call foregin key table, is called as check table in SAP.
    Reward points for the answer

  • Looking for a formula to calculate difference between two values

    So, heres my problem...
    I have a set of incremental values which act as thresholds, 100, 200, 300, so on. Another number is independent and correlates to that set of values, say 148.
    I want another cell which calculates the difference between 148 and 200, but then recognises that when 148 goes over 200 that the next threshold has been met, so then resets and starts calculating the difference between that new number and the next threshold,
    300.
    Is it possible to do this all in the same cell?
    Thanks in advance.

    Re: variable number difference
    With the independent number in cell F8, maybe...
      =IF(MOD(F8,100)=0,0,100-MOD(F8,100))
    Jim Cone
    free & commercial excel programs (n/a xl2013)
    https://jumpshare.com/b/O5FC6LaBQ6U3UPXjOmX2

  • Sum values in last row for date format "hh24:mi"

    Hi,
    I have a big problem creating a sum row with date data.
    I created a sql view where the result looks like that:
    SELECT category_name,
    user_name,
    b_mmyyyy,
    b_1, ..., b_31
    FROM view_category_user_booking
    category_name, user_name, b_1, ..., b_31
    category1, user1, 122008, 01:00, ..., 03:30
    category2, user1, 122008, 02:00, ..., 01:00
    category3, user1, 122008, 00:00, ..., 00:15My goal is to integrate a sum row at the end for the columns b_1 ... b_31
    category_name, user_name, b_1, ..., b_31
    category1, user1, 122008, 01:00, ..., 03:30
    category2, user1, 122008, 02:00, ..., 01:00
    category3, user1, 122008, 00:00, ..., 00:15
    Sum, user1, 122008, 03:00, ..., 04:45I tried it like that:
    select decode(grouping(category_name),1,'Summe',category_name),
    sum(to_number(replace(b_1,':',','))) as b_1,
    sum(to_number(replace(b_31,':',','))) as b_31
    from category_user_booking
    where user_name = 'user1'
    and b_mmyyyy = '122008'
    group by rollup(category_name)But the result isn't really successful
    category_name, b_1, b_31
    category1, 1, 3,3
    category2, 2, 1
    category3, 0, 0,15
    Sum, 3, 4,45Is there somebody with an idea?
    Thanks ahead,
    Tobias

    Hi Avinash,
    the problem is not the grouping it is the date format.
    Instead of a value like 5,4 > I want 05:40 or 1,75 > I want 02:15 in the sum value.
    In my table all time values are saved in the format hh24:mi.
    I don't know how to get that via a sql statement.
    Output I want:
    category_name, user_name, b_1, ..., b_31
    category1, user1, 122008, 01:00, ..., 03:30
    category2, user1, 122008, 02:00, ..., 01:00
    category3, user1, 122008, 00:00, ..., 00:15
    Sum, user1, 122008, 03:00, ..., 04:45Regards,
    Tobias

  • Difference between audigy value and sound blas

    Since i am unable to find comparisions between soundblaster 24bit and AudigyValue in site , Anyone can give me the difference between these two ?

    Other than the name, not much. Both cards lack the EMU0K/2 chip, and have to do all processing in software (cpu processing instead of on the card). Oh yeah and the Audigy SE has newer drivers than the Value (and will probably install on the SB 24 bit).
    All things considering if you are looking at a card for gaming (or just about anything else) avoid both of them.

  • OSB to Object Types: difference between NULL value and not available

    Hello all,
    I have a question about Object Types. More specifically, how to differentiate between an empty value (null) and a string not available.
    This is my case:
    I have created an object type with three parameters.
    CREATE OR REPLACE TYPE OSB_EMP_OBJ_TYPE AS OBJECT
    (EMP_ID NUMBER
    ,DEPT_ID NUMBER
    ,ORDER_ID NUMBER
    ,CONSTRUCTOR FUNCTION OSB_EMP_OBJ_TYPE
    RETURN self as result
    /I would like to see what happens when I put an empty string into emp_id, NULL into DEPT_ID and nothing into ORDER_ID.
    To do so I have this test script:
    declare
      p_emp OSB_EMP_OBJ_TYPE := OSB_EMP_OBJ_TYPE();
    begin
      p_emp.EMP_ID := '';
      p_emp.DEPT_ID := null;
    --  p_emp.ORDER_ID := null;
      if p_emp.EMP_ID is null
      then
        dbms_output.put_line('Empty');
      end if;
      if p_emp.DEPT_ID is null
      then
        dbms_output.put_line('NULL');
      end if;
      if p_emp.ORDER_ID is null
      then
        dbms_output.put_line('Not available');
      end if;
    end;The result of this is:
    Empty
    NULL
    Not availableIt seems that Oracle treats all three situations alike. What I would like to achieve is a way to see that p_emp.ORDER_ID was not initialized.
    To elaborate a bit: in our production system this procedure would be called from OSB and the object type would by the input for that procedure. Our database version is 10.2.0.5.0.
    Our procedures look something like this:
    procedure p_procedure ( p_emp in osb_emp_obj_type )
    is
    begin
      do_something;
    end;Can anyone tell me if there is a way to achieve this, so I can see whether or not a value in the object type was filled?
    Thanks in advance!

    Darn...
    Eventually we want to use this for an update procedure. The client gets all current data from the database by calling a webservice that (using OSB) selects the data from our database. What we want to achieve is that the client can update that data, by returning only the changed fields to an update procedure.
    We then handle an empty tag to update the field to null, and we ignore missing tags.
    OSB itself can handle this, but PL/SQL can't.
    I'm now thinking of adding an indicator to each optional field (clear_field_yn). OSB can still check for empty tags or missing tags. When a tag is empty, it's corresponding indicator will be set to 'Y'. If the tag is missing, then it will be set to 'N'.
    Is that a solution to consider, or is there a much simpler approach possible?

  • Difference between cash value after customs and before customs?

    Hello experts.
    Where can you percieved the diffrerence on the landed costs if you select the allocation by before/after customs?
    Looking forward to your reply,
    Kind regards

    Hi Erickson,
    In the landed cost you can allocate your customs cost. Customs cost allocation to items can be difference per item customs cost percentage (as defined in the master data) or based on total cost allocation (actual customs in the landed cost screen).
    If your landed cost allocated to total value after custom, then that cost will be allocated based on item value after customs (item cost + customs).
    Example:
    1. Item A; Value 500; customs rate : 10%
    2. Item B; Value 1500; customs rate: 15%
    Total landed cost 2000
    Landed Cost Allocation:
    => cash value before customs:
    1. Item A
         => Customs = 10% * 500 = 50
         => Landed cost = (500/2000) * 2000 = 500
         => final cost Item A = (item cost + customs + landed cost) = 500 + 50 + 500 = 1050
    2. Item B
         => Customs = 15% * 1500 = 225
         => Landed cost = (1500/2000) * 2000 = 1500
         => final cost Item A = (item cost + customs + landed cost) = 1500 + 225 + 1500 = 3225
    => cash value before customs:
    1. Item A
         => Customs = 10% * 1000 = 100
         => Cash value after Customs = 500 + 100 = 600
         => Landed cost = (600/2275) * 2000 = 483.52
         => final cost Item A = (item cost + customs + landed cost) = 500 + 100 + 483.52 = 1033.52
    2. Item B
         => Customs = 15% * 1500 = 225
         => Cash value after Customs = 1500 + 225 = 1725
         => Landed cost = (1725/2275) * 2000 = 1516.48
         => final cost Item A = (item cost + customs + landed cost) = 1500 + 225 + 1516.48 = 3241.48
    => If actual customs directly being input into landed cost screen, the would be no difference on the landed cost allocation since all customs allocated proportionally.
    Cheers

  • Difference between Apple TV and Front Row?

    Right now I have a Mac Mini with Front Row hooked up to our 1080p HDTV. With Front Row we can watch any movies we've downloaded from iTunes and all our home movies on the TV and they look great. I've never used or seen an Apple TV in action. What more does it do than Front Row? Will the HD versions of movies for rent on iTunes only be available for the Apple TV?

    So it looks like the the only advantage on having the Apple TV is the HD video rental through iTunes. The pros on the MacMini far outweigh the pros on the Apple TV. It's just a matter of how much I want to be able to rent HD movies from iTunes. The MacMini can totally handle the HD content playback (I shoot HD home movies all the time and play them back on Front Row on our MacMini to the HDTV and it has no problem) so I wonder why they are restricting the HD video rentals to the Apple TV.
    And, by the way, you can connect the MacMini via HDMI by getting a DVI to HDMI cable and then taking the audio from the digital audio out. It's the way I have it set up now and it looks and sounds great.

  • Expanding table: Calculating difference to value from previous row

    Hi there,
    I am a complete newbie to LiveCycle Designer (ES2) and have created below document with an expanding table.
    Shared Files - Acrobat.com
    My aim is to make the form user friendly by adding a calculation in the field "Twist" which calculates the difference from the current row to the previous row.
    I have no idea about Java Script, I am afraid, and also don't know if this is possible at all so it's probably a bad idea after all.
    The reason for setting it up as an expanding table is so that the form can be used for all 32 instances the form would be used for (they would all require different amount of rows altogether).
    The calculation would start in row 2 (Checklist.Table1), take the twist value entered in row 2 and calculate the difference to the twist value entered in row 1.
    Then in row 3, it would calculate the difference between twist value in row 3 to row 2 etc.
    So subtract value of field in rown with value in rown-1 or something in this direction.
    Is there anyone at all who could help me with this at all?
    I'd be very grateful for any advice you could give me.
    Thanks a lot!
    Mathilda

    Not sure what happened with the formatting there, try this;
    if (Row1.index > 0 && !Row1.resolveNode("NumericField4[0]").isNull)
        var prevTwist = Table1.resolveNode("Row1[" + (Row1.index - 1) + "].NumericField4[0]").rawValue
        var result = Math.abs(3000 / (Row1.resolveNode("NumericField4[0]").rawValue - prevTwist));
       this.rawValue = result;
    else
        this.rawValue = "";

  • Code to genereate difference between succcessive dates in a table

    First create and Insert statements;
    create table schedule(iloan_code number , schedule_date date);
    insert into schedule values(1001, to_date('01-jun-2012'));
    insert into schedule values(1001, to_date('01-jul-2012'));
    insert into schedule values(1001, to_date('01-aug-2012'));
    insert into schedule values(1001, to_date('01-sep-2012'));
    insert into schedule values(1001, to_date('01-oct-2012'));
    commit;THe output of the SCHEDULE table shall be now like this:
    ILOAN_CODE     SCHEDULE_DATE
    1001              01-JUN-12
    1001              01-JUL-12
    1001              01-AUG-12
    1001              01-SEP-12
    1001              01-OCT-12we want an extra column by name DAYS along with the existing columns which would be the difference between the dates.
    First row should be the difference between sysdate and the date 01-jun-2012 and the successive rows must be the difference between successive schedule dates
    For instance in the second row the DAYS column must represent the difference between 01-jul-2012 and 01-jun-2012 and so on for the next rows too.
    We need to get the output through a SELECT statement
    The output of the SCHEDULE table must be somthing like this.
    iloan_code      schedule_date     days     Logic which we need
    1001     1-Jun-12     22     sysdate-1st June 2012
    1001     1-Jul-12     30     difference between 1st July 2012 and 1st June 2012
    1001     1-Aug-12     31     difference between 1st aug 2012  and 1st July 2012
    1001     1-Sep-12     31     difference between 1st sep  2012 and 1st aug  2012
    1001     1-Oct-12     30     difference between 1st oct 2012 and 1st sep 2012Please advise;

    Hi,
    sri wrote:
    ... Could you please let me know the formatting procedure used for the output . I have used (code) (code) (you can consider ( for { ) concept but could not display the
    expected results properly.I'm not sure what you're saying.
    To preserve spacing, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text.
    Alternatively, you can use these 6 characters
    &#091;code&#093;
    (case insensitive, inside square brackets) at the beginning of a formatted section, and these 7 characters
    &#091;/code&#093;
    (with a forward /) at the end of the formatted section.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Difference between report mc49 and MC48

    HI,
    i would like to display stock value (in order to date and purchase group) in report MC48 and MC49. The value is different becouse report MC48 shows average stock value and mc49 just stock value. What arleady means "average stock value"? What is the difference between stock value and average stock value?
    Thanks in advance
    Kasia Gac

    Hi Kazia,
    MC48 shows the stock value at the end of the period you enter on the selection screen. The default here is the last 3 months.
    MC49 shows you the average stock value for that period.
    Best,
    Ralf

  • Difference table size values

    Hello Experts,
    I want to know the sizes of some tables (e.g. TCURR). In different threads the transaction db02old and the function module 'DB_GET_TABLE_SIZE' are mentioned for that purpose.
    I wonder that using these methods two different sizes are
    Using transaction db02old I get a size of  81.920 for TCURR.
    Using function module 'DB_GET_TABLE_SIZE' I get a size of 79.937 for TCURR. Why is there a difference between both values?
    Thanks for your help.
    Regards,
    Tobias

    DB02old  gives the correct information as it directly updates value from Database.
    Function module 'DB_GET_TABLE_SIZE' depends on the variables you have set and it useful for ccms operations.
    regards
    nag
    Edited by: welcomenag on Jul 6, 2009 4:15 PM

Maybe you are looking for