Compare previous row values for the same id and decide

Hello ,
I have this sample data
create table #student_academic
pk_id int identity(1,1) primary key ,
student_id int ,
[year] int,
[aggr_marks] float
insert into #student_academic
student_id ,
[year] ,
[aggr_marks]
values
(112,2012,55.4),(113,2012,65.4),(114,2012,82.32),
(112,2013,75.4),(113,2013,91.22),(114,2013,45.45),
(112,2014,61.2),(113,2014,95.2),(114,2014,75.6)
select * from #student_academic
from the above data i have to generate an extra status column. this status column should be decided by comparing the previous row value. the exact output should be like below.
student_id year aggr_marks Staus----------------------------------------------------------
112 2012 55.4 None
112 2013 75.4 Promoted
112 2014 61.2 Demoted
113 2012 95.2 None
113 2013 75.6 Demoted
113 2014 91.22 Promoted
113 2012 45.45 None
113 2013 65.4 Promoted
113 2014 82.32 Promoted
is there any way to write the t-sql with out using cursors ? this table has around 25GB of data. Any idea would be appreciated.
Thanks in advance.

Hello,
The difficulty of your example is
that there are several rows for
the same year and the same student.
I present a solution
if there is
one line per year per
student:
TRUNCATE TABLE #student_academicinsert into #student_academic
student_id ,
[year] ,
[aggr_marks]
values
(112,2012,55.4),(113,2012,65.4),(114,2012,82.32),
(112,2013,75.4),(113,2013,91.22),(114,2013,45.45),
(112,2014,61.2),(113,2014,95.2),(114,2014,75.6)
Go
WITH CTE AS
(SELECT pk_id, student_id, year, aggr_marks,
(SELECT TOP 1 aggr_marks FROM #student_academic AS b
WHERE a.student_id = b.student_id AND a.year -1 = b.year
ORDER BY student_id) AS prev_aggr_marks
FROM #student_academic AS a
SELECT
pk_id, student_id, year, aggr_marks,
CASE
WHEN prev_aggr_marks IS NULL THEN 'None'
WHEN aggr_marks < prev_aggr_marks THEN 'Demoted'
WHEN aggr_marks >= prev_aggr_marks THEN 'Promoted'
END AS Status
FROM CTE
ORDER BY student_id, year
Regards,
Charlie
Charlie Dancoisne - Independent Consultant & Trainer (Please take a moment to "Vote as Helpful" and/or "Mark as Answer", where applicable. This helps the community, keeps the forums tidy, and recognises useful contributions. Thanks!)

Similar Messages

  • Creation of a Query to show the values for the current month and the last 12 months data.

    Dear All,
    Good day!
    I have to create a Query with the below requirement.
    I have to create a Query to show the values for the current month and the last 12 months data.
    Can you please guide me how to achieve this ??
    thank you,
    Regards,
    Hema

    Hema
    explain the exact problem..? as you mentioned you want to create query to show values for current month and last 12 months.. so I think you want to show values for 12 months from current data.. you can achive this by multiple way..
    you can have selection screen and field with date .. and restrict based on system current date and 12 months before or you can handle this at your target.. .. I mean there are multiple ways to restrict data by date range..
    for some more hints..
    http://www.forumtopics.com/busobj/viewtopic.php?t=34393&sid=7fba465d0463bf7ff5ec46c128754ed6
    http://businessintelligence.ittoolbox.com/groups/technical-functional/cognos8-l/how-to-display-last-12-months-in-report-based-on-todays-date-3231850
    http://scn.sap.com/thread/3217381
    search on SDN you will get many other ways..
    Thanks,
    Bhupesh

  • I used to give my photo's keywords. Most of the time I have several photo's for the same keyword and it was possible to select all those photo's and give them the keyword in one move. Since of few weeks I can't do that anymore and I find it very annoying.

    I used to give my photo's keywords. Most of the time I have several photo's for the same keyword and it was possible to select all those photo's and give them the keyword in one move. Since of few weeks I can't do that anymore and it's very annoying. What can I do to get back to the former situation?

    . Since of few weeks I can't do that anymore and it's very annoying. What can I do to get back to the former situation?
    Check, if you have the "Primary Only" option enabled. Then keywords will only be applied to the "Primary Image":
    See:                  Keywords or ratings are applied only to one of the selected images - why?
    Uncheck the little square button with the "1".

  • Default values for the controlling area and language

    Hello
    I have a query.
    I need to set default values for the controlling area and language in the screen
    "find account assignment data 1"
    Is it possible to do so?
    Thanks.
    Jayawant Gokhale

    Hello
    To clarify,
    This is the search used ,when I go for shopping.For the Cost assignment,the fields controlling area and language should be default for a user.
    Could someone throw a light on this.
    Thanks.

  • Need to set default values for the fields plant and location in ME21N

    Hi All,
    i need to set default values for the fields plant and location in ME21N tcode.
    In accout assignment if we give 'A' then we need to create asset by clicking the Asset tab,there you have the fields plant and location.
    How to resolve this?
    Thanks in Advance

    hi .
    i needed to set default strorage location and plant in personal setting  in me21n.
    i solve it with this way.
    go to program SAPLMEPERS in se38.
    create new function in output with the sample name :MODULE ZTEST_001 OUTPUT.
    in this module write:
    if MEPOITEM_PROP-WERKS is INITIAL and  MEPOITEM_PROP-LGORT is INITIAL.
    MEPOITEM_PROP-WERKS = '1000'.
    MEPOITEM_PROP-LGORT = '0032'.
    endif.
    this is the solution.
    best regards.
    maryam

  • "Show List of values"  showing different values than "Preview List of values for the same dimension Object

    Hi All, 
    I have a dimension object in Business Layer which is showing a different values than the original database values. When I right click on the object and select "Show List of Values its showing values which are not related to the original values in the database but if I right click on the same object and select "Preview List of Values" it shows the right values present in the database. Any suggestions on how to rectify. It was working good and many reports have been built using that particular dimension.
    Is there any way to fix the problem without the deleting the object or recreating another similar object as the object has been used in several reports, so by deleting or recreating the object may break the reports.
    Please help!

    Hi
    A  list of values is a list that contains the data values associated with an object, Lists of values inserted in the data foundation are inherited by any business layer based on the data foundation.
    Right click on the object and select  “Show Values”… Display all the DB values including null
    Preview List of Values – also display same values...getting differnece meens...Check weather using any Static List of Values.
    If you uncheck the Associated list of values check box "Preview List of Values" options is disabled.
    For best practice …LOV is disabled for un-necessary dimension objects
    Also If you have Db access check the correct data by
    SELECT
    Distinct Schema name. Table/View name. Object name
    FROM
    Schema.name. Table/View name

  • Filter the content on different queries for the same infoprovider and user

    Hello,
    We are trying to make the following security scenario in BI, and have
    problem with the analysis object concept to filter at query level.
    The idea is to permit to :
    - user A
      - to execute query Q1 and view information about sites 1,2,3
      - to execute query Q2 and view information about sites 4,5,6
    but for example for another user :
    - user B
      - to execute query Q1 and view information about site 1,3
      - to execute query Q2 and view information about site 5,6,7
    Q1 and Q2 are queries from the same infoprovider.
    The idea is to make an automatic generation of analysis objects based
    on the standard program : RSEC_GENERATE_AUTHORIZATIONS.
    During tests, we have faced a problem with the object 0TCTQUERY that we
    thought will permit us to filter at the query level, but unless we add
    the name on the query on a role in the S_RS_COMP authorization object,
    field RSZCOMPID, the query is not granted to the user.
    The fact that we use both authorization objects : one for the query
    definition, and another for the analysis authorization concept
    (S_RS_AUTH, field BIAUTH), has disastrous effect : all values given in
    the analysis objects are for all queries of an indicated infoprovider.
    With that system, it's then not possible to propose dynamically different
    views of the same data (ie from same infoprovider) based on the
    authorization concept unless using the technic of customer-exit variable,
    but with variable you will have a problem with old queries that doesn't
    have a variable and that will permit to see all data given in the new
    authorization objects.
    Is there exists another object to filter at the query level in the
    analysis objects ? If it's not the case, what is possible to do to reach
    our goal with the new authorization concept ?
    Thank you in advance for your help.
    Best regards,
    Gaël.

    The data is protected on infoprovider level and not on the query level,  so when two querys are build from the same Infoprovider then the authorizations are the same,
    To achieve what you want to do,  the querys must be built off different providers.   This can be achieved by placing the infoprovider in 2 differnt multiproviders and building the querys and authorizations seperatly on these.

  • I'm being charged three times for the same service and I can not use it

    Hello, A few months ago I tried to buy Adobe Creative Cloud when putting the data on the card told me that there was a mistake, then I tried other cards ... in short, I'm being charged three times for the same product twice a card and once in another obviously no "mistakes", the problem is that I can not use the product. I want to give low in all three accounts and also be compensated for the time they have charged me three times. Please, I need to solve this urgent problem.

    This is an open forum, not Adobe support... You need Adobe support to cancel a subscription
    -cancel http://helpx.adobe.com/x-productkb/policy-pricing/return-cancel-or-change-order.html
    -or by telephone http://helpx.adobe.com/x-productkb/global/phone-support-orders.html

  • Double service entry sheet for the same invoice and same period

    Hi,
    2 service entry sheets have been made for the same PO with the same period and the same invoice no. And hence by mistake 2 bills have been passed for the same work...
    how to avoid this.....
    is there any std.setting available while creating service entry sheet.
    Plz. help
    Navin

    If there is sufficient quantity in the PO, this cannot be prevented by the system.
    Have the data entry person write the SE Sheet number on the physical copy of the bill so that another person entering it can see that SE Sheet is done.
    Hope this helps,
    Lakshman

  • HT204088 I was charged twice for the same purchase and I can't find a place to make contact for a refund from the iTunes store...

    ON August 7th this year I purchased  an ibook and was charged twice for the same book, so I would like to get a refund for one ...
    Where can this trensaction be done? I'm having a problem finding the location.

    You can contact iTunes support here and ask for a refund/credit for the duplicate charge : http://www.apple.com/support/itunes/contact/ - click on Contact iTunes Store Support on the right-hand side of the page, then Purchases, Billing & Redemption

  • [ora_hash] different value for the same input

    hi all,
    i'm using 2 different machine running the same version of oracle (11g).
    on those 2 db i have the same tables with the same datas.
    for the comparisson of the data i'm using the ora_hash function (both on numeric and string fields) and for some records i get different results.
    how is that possible?
    (by the way looking at the records that has different hashes the values calculated by the hash function are the same)
    thx

    You have posted in the wrong forum. As the forum title says this forum is for SQL Developer and not for SQL or PL/SQL questions.
    After reading the information provided at the end of this reply you should
    1. create a new thread in the SQL and PL/SQL forum
    PL/SQL
    2. Edit this current question to add a link to the new question and tell people to follow up in the other forum.
    3. Mark this current question ANSWERED so followup will be in the other forum.
    Thanks.
    When you post in the other forum provide information related to the following
    >
    for the comparisson of the data i'm using the ora_hash function (both on numeric and string fields) and for some records i get different results.
    >
    Please post your 4 digit Oracle versions - both versions (result of SELECT * FROM V$VERSION) and examples (i.e. actual code) of values that are giving different results.
    >
    (by the way looking at the records that has different hashes the values calculated by the hash function are the same)
    >
    What? there can't be 'different hashes' if the 'values calculated by the hash function' are the same. What are you saying here?
    Again - provide examples that show the differences. Should be something like
    SELECT ORA_HASH(12345) FROM DUAL;Since you say there are differences on the two machines provide the execution plan from each machine that shows what Oracle is actually doing. One machine may be applying a function to the data.

  • How can I create a hashmap() with multiple values for the same key?

    I am trying to write an application that will us something like a Map() with multiple values but some have the same key. Is this possible?

    i had the same question. just create a List, add all the values u want to it, and then put the List into the map like u would a normal single value. e.g.
    List list = new ArrayList();
    list.add(value1);
    list.add(value2);
    map.put(key, list);
    i bet u r doing the same course as i am =)

  • Different results for the same query and same data !  (oracle 9i)

    Hi,
    This is a mystery for me. I've got on my database exactly the same data that my customer (exported schema). We both launch the same query (generated by the software that we sold him). This query has a criteria IN (SELECT MAX()...) to get only data from the last year.
    The query gives 477 rows on my computer (correct answer), but no row on his! We have the same data! The only difference is the Oracle release : 9.2.0.6.0 for him, 9.2.0.1.0 for me.
    If he executes the subquery alone, it gives the expected result.
    If he replaces the MAX() in the subquery by the returned value (year 2016), he gets his 477 rows.
    I've rewritten the query with a NOT EXISTS, and now all is fine. (Less efficient but it works).
    I have no rational explication. Did I miss something ?
    Thanks for any answer.
    This is the query:
    SELECT ...
    FROM
    CRA, GRA, ...
    WHERE
    /* subselect */
    (CRA.COLLCOD, CRA.CRANEXE, CRA.CRANCODBUD, CRA.GRANNUM, CRA.CRANCOD1, CRA.CRANCOD2, CRA.CRANCOD3, CRA.CRANCOD4)
    IN (
    SELECT b.COLLCOD, MAX(cranexe), b.CRANCODBUD, b.GRANNUM, b.CRANCOD1, b.CRANCOD2, b.CRANCOD3, b.CRANCOD4
    FROM CRA b
    GROUP BY b.COLLCOD, b.CRANCODBUD, b.GRANNUM, b.CRANCOD1, b.CRANCOD2, b.CRANCOD3, b.CRANCOD4
    AND... /* other filters and joins */

    v9.2.0.1 was full of bugs. a lot of these bugs had to do with "incorrect results", typically associated with old stats or complex queries (certain types of subqueries were very likely to give wrong resutls, due to the way they were rewritten by the optimizer).
    apply the 9.2.0.6 patch set

  • Changed Ulimits values for the Oracle user and getting error -bash: ulimit: max user processes: cannot modify limit: Operation not permitted when logging in.

    I'm trying to increate the ulimits for max user processes and open files for the oracle user.  I've set the values in limits.conf, /etc/profile and in oracle's environment scripts. Now when I log in as oracle I get the below errors. If I change the ulimits back to the original values errors go away but ulimits aren't changed.
    login as: oracle
    [email protected]'s password:
    Last login: Fri Mar  6 09:56:02 2015 from mtkadmin12
    You are logging onto an Oracle system.
    Kickstarted on: 2014-06-05
    -bash: ulimit: max user processes: cannot modify limit: Operation not permitted
    -bash: ulimit: max user processes: cannot modify limit: Operation not permitted
    [oracle@servername ~]$

    Thanks for the update.
    I modified the /etc/security/limits.d/90-nproc.conf and added a line for oracle and also modifed the oracle.sh file.  The ulimits are setting correctly when I su - oracle but they are still wrong when sshing in as oracle.
    [root@mtkdevorap11d-1 ~]# su - oracle
    [oracle@mtkdevorap11d-1 ~]$ ulimit -Ha
    core file size          (blocks, -c) unlimited
    data seg size           (kbytes, -d) unlimited
    scheduling priority             (-e) 0
    file size               (blocks, -f) unlimited
    pending signals                 (-i) 1030982
    max locked memory       (kbytes, -l) 94371840
    max memory size         (kbytes, -m) unlimited
    open files                      (-n) 65536
    pipe size            (512 bytes, -p) 8
    POSIX message queues     (bytes, -q) 819200
    real-time priority              (-r) 0
    stack size              (kbytes, -s) unlimited
    cpu time               (seconds, -t) unlimited
    max user processes              (-u) 16384
    virtual memory          (kbytes, -v) unlimited
    file locks                      (-x) unlimited
    [oracle@mtkdevorap11d-1 ~]$
    [oracle@mtkdevorap11d-2 ~]$ ssh mtkdevorap11d-1
    Last login: Mon Mar 16 13:04:16 2015 from mtkdevorap11d-2.conveydev.com
    You are logging onto an Oracle system.
    Kickstarted on: 2014-06-05
    [oracle@mtkdevorap11d-1 ~]$ ulimit -Ha
    core file size          (blocks, -c) unlimited
    data seg size           (kbytes, -d) unlimited
    scheduling priority             (-e) 0
    file size               (blocks, -f) unlimited
    pending signals                 (-i) 1030982
    max locked memory       (kbytes, -l) 64
    max memory size         (kbytes, -m) unlimited
    open files                      (-n) 4096
    pipe size            (512 bytes, -p) 8
    POSIX message queues     (bytes, -q) 819200
    real-time priority              (-r) 0
    stack size              (kbytes, -s) unlimited
    cpu time               (seconds, -t) unlimited
    max user processes              (-u) 16384
    virtual memory          (kbytes, -v) unlimited
    file locks                      (-x) unlimited
    [oracle@mtkdevorap11d-1 ~]$

  • Multiple event handlers registered for the same event and error when adding users to sec groups

    Project Server 2013 CU April (May) 2014
    I've created and installed two event handlers (separate dll:s) and both are triggering on Project Published - initially, both are working fine.
    After an IISReset, trying to create a new security group (or add a user to an existing group) will result in an error on the page and a corresponding error in the ULS log - the latter indicating an error in the method security.creategroups, and specifically
    a problem 'An item with the same key has already been added.'
    An SQL trace reveals a break in execution after executing the proc 'pub.MSP_ADMIN_ReadEventReceivers' which returns all registered event handlers.
    In my case, the result of that proc execution shows that there are two event handlers registered with an EVENT_ID of 53 (Project Published) and with ORDER_FIRED set to 1 and 2 respectively.
    I tried removing one of the event receivers using the Central Admin PWA interface and then everything worked just fine - I added the event receiver back again, and everything STILL worked! IISReset and I got the error back again. :-(
    Since there's obviously some problem with reading multiple entries from that table regardless of the ORDER_FIRED differentiation, I tried temporarily modifying one of the '53' entries in the table directly and then the sec group was created just fine!
    I would like to know if anyone else has seen this? I've seen this on three separate installations now after deploying a second event listener onto those systems.
    /Lars Hammarberg
    //Lars Hammarberg www.connecta.se

    Hi Lars,
    yes I have seen the same issue. It is not related to April CU. I had the error before with SP1.
    It is not only an issue with the security groups. At least in our case nothing worked at all. No custom field editing, all Queue Jobs failing.
    For your case I suggest you consolidate your code in one eventhandler.
    Theory says that you can have more than 1 (up to 999) eventhandlers for one Event (http://msdn.microsoft.com/en-us/library/ms481079(v=office.12).aspx) but that seems not to
    work. Not sure, if it worked in earlier versions.
    Kind regards
    Christoph
    Christoph Muelder | Senior Consultant, MCTS, MCSE, MCT | SOLVIN information management GmbH, Germany

Maybe you are looking for

  • I'm having major issues and I'm fed up!

    I got a nano in July, and I use it ONLY to listen to audio book. This is an issue in itself. If a book isn't available at the itunes store (I get books from the library) I can not get info on it, and the only way to listen to it is through recently a

  • Maximum number of photos in Photoshop Elements 8

    I am using Photoshop Elements 6 and am considering upgrade to 8. I am using Windows XP. I have about 50,000 photos on 6 and wonder what experienced users feel is the limit on 8 (or on Elements in general). Am I better off dividing into multiple catal

  • How to expose a Delegate feature of BPM workspace to oracle primavera

    Hi All, We have Oracle primavera which is getting used for Project portfolio management and we are using BPM workflows to manage it. All the Human task pages are designed on ADF which can be accessed directly from Oracle Primavera application by user

  • Ad Hoc Query Designer - Web Application

    Hello, I have created a Web application that has the 'Ad-Hoc Query Designer' item. When I go to create a new query I don't have the option (or I can't find it) to use any variables. Like in Analyzer I can run a query and it will ask me the values for

  • Linking two KM systems

    Hi, I want to link two 2004s KM systems. One KM should be the main system to hold the repository with all data. The second system should use the same repository as the first one and shall build only a interface to the first system. The reason why I w