How to get this with Single query

Friends
I am sure using SQL analytical function, the following can be achieved using a single query:
Date_value | Cust_id | Customer_tenue | avg_bal
01-aug-09 | 111 | 0 | 1000
01-aug-09 | 112 | 1 | 2000
01-aug-09 | 113 | 2 | 900
01-aug-09 | 114 | 3 | 1250
01-sep-09 | 111 | 1 | 1200
01-sep-09 | 112 | 2 | 2000
01-sep-09 | 113 | 3 | 1900
01-sep-09 | 114 | 4 | 1250
01-oct-09 | 111 | 2 | 1100
01-oct-09 | 112 | 3 | 2200
01-oct-09 | 113 | 4 | 1900Expected result
If customer’s tenure is 0 then mark as ‘New’,
If customer’s balance is increased from last month then mark as ‘Augment’
If customer’s balance is same as last month then mark as ‘Maintain’
If customer’s balance is decreased from last month then mark as ‘Diminish’
Else ‘Left’
Help please....

If customer’s tenure in last month is 0 then mark as ‘New’,There's not such case in test data... last month is October, isn't it?
SQL> with t as (select DATE '2009-08-01' Date_value, 111 Cust_id, 0 Customer_tenue, 1000 avg_bal from dual union all
  2  select DATE '2009-08-01', 112 , 1 , 2000 from dual union all
  3  select DATE '2009-08-01', 113 , 2 , 900 from dual union all
  4  select DATE '2009-08-01', 114 , 3 , 1250 from dual union all
  5  select DATE '2009-09-01', 111 , 1 , 1200 from dual union all
  6  select DATE '2009-09-01', 112 , 2 , 2000 from dual union all
  7  select DATE '2009-09-01', 113 , 3 , 1900 from dual union all
  8  select DATE '2009-09-01', 114 , 4 , 1250 from dual union all
  9  select DATE '2009-10-01', 111 , 2 , 1100 from dual union all
10  select DATE '2009-10-01', 112 , 3 , 2200 from dual union all
11  select DATE '2009-10-01', 113 , 4 , 1900 from dual)
12  select date_value, cust_id, avg_bal, oldbal, case when Customer_tenue=0 and nextbal is null then 'NEW'
13                                                    when oldbal<avg_bal then 'Augment'
14                                                    when oldbal=avg_bal then 'Maintain'
15                                                    when oldbal>avg_bal then 'Diminish'
16                                                    else 'Left' end status
17    from (select date_value, cust_id, customer_tenue, avg_bal, LEAD(avg_bal) over (partition by cust_id order by date_value desc) oldbal,
18                 LAG(avg_bal) over (partition by cust_id order by date_value desc) nextbal
19            from t)
20  order by cust_id, date_value;
DATE_VALU    CUST_ID    AVG_BAL     OLDBAL STATUS
01-AGO-09        111       1000            Left
01-SET-09        111       1200       1000 Augment
01-OTT-09        111       1100       1200 Diminish
01-AGO-09        112       2000            Left
01-SET-09        112       2000       2000 Maintain
01-OTT-09        112       2200       2000 Augment
01-AGO-09        113        900            Left
01-SET-09        113       1900        900 Augment
01-OTT-09        113       1900       1900 Maintain
01-AGO-09        114       1250            Left
01-SET-09        114       1250       1250 Maintain
Selezionate 11 righe.Max
[My Italian Oracle blog|http://oracleitalia.wordpress.com/2009/12/29/estrarre-i-dati-in-formato-xml-da-sql/]

Similar Messages

  • Getting Counts with single query

    HI,
    I need help in writing a query that gets account counts in a single query,
    CREATE TABLE ACCOUNTINFO(     
    ACCOUNTID VARCHAR2(20 BYTE) NOT NULL,
    ACCOUNTNO VARCHAR2(10 BYTE) NOT NULL,
    LAST_DEPOSIT_DATE DATE,
    BALANCE NUMBER(10,0));
    I have a table like above and I am trying to write a query that gets
    Count of accounts with deposits made in last 1 month,
    Count of accounts with deposits made in last 2 months
    Account Count with balance > 0,
    Also, I need to join this ACCOUNTINFO with ACCOUNTMAIN to get name etc details
    CREATE TABLE ACCOUNTINFO(     
    EMPID VARCHAR2(20 BYTE) NOT NULL,
    FNAME VARCHAR2(30 BYTE) NOT NULL,
    MNAME VARCHAR2(30 BYTE),
    LNAME VARCHAR2(30 BYTE) NOT NULL,
    DOB DATE,
    ACCOUNTID VARCHAR2(20 BYTE));
    Question, how to write a query since I getting too-many counts (I have only 3 in sample above, actual goes on like 3-6, 6-9 etc).

    SELECT SUM  (CASE WHEN LAST_DEPOSIT>=ADD_MONTHS(SYSDATE,-1) THEN
                   1
                 ELSE
                   0
                 END
                ) COUNT_LAST_MONTH,
           SUM  (CASE WHEN LAST_DEPOSIT>=ADD_MONTHS(SYSDATE,-2) THEN
                   1
                 ELSE
                   0
                 END
                ) COUNT_LAST_TWO_MONTHS,
           SUM  (CASE WHEN BALANCE>0 THEN
                   1
                 ELSE
                   0
                 END
                ) COUNT_BALANCE_GREATER_ZERO
      FROM ACCOUNTINFO

  • Getting result with single query

    Hi,
    I'm using db 10.2.0.1.0
    I have a table emp_shift , with data like below
    EmpCode           Shift     Effdate            Default
    1                 SHFT1    02-jan-2012          N
    1                 SHFT2    04-jan-2012          Y
    1                 SHFT3    04-jan-2012          NSo if user inputs EmpCode and Effdate, based on that i've to take the latest record, with default = 'Y' (if any) else default 'N'
    Suppose
    Case 1 : Input Empcode:1 Date:10-jan-2012
    Then i should get the below record
    1                 SHFT2    04-jan-2012          YCase 2 : Input Empcode:1 Date:03-jan-2012
    Then i should get the below record
    1                 SHFT1    02-jan-2012          NI want this result with a single query, is this possible?
    Thanks
    Divya

    Hi Thank you both,
    I'm trying this process through forms. and my forms version is 6i.
    There where i'm trying the query with the cursor, i'm getting error
    Encountered the symbol Order when expecting one of the following
    .()...and my cursor is
    Cursor cur_shft(vemp Varchar2,vdate Varchar2) is Select ESM_SHIFT_TYPE
         from (Select ESM_SHIFT_TYPE from EMPLOYEE_SHIFT_MASTER
                   Where ESM_EMP_CODE = vemp
                   and ESM_EFF_DATE <= vdate
                   Order by ESM_EFF_DATE desc,Esm_Default desc)
                   Where rownum=1 ;Whats wrong?

  • How to do this with one query?

    here is the basic query
    <cfquery name="getCenturies"
    datasource="#application.dsn#">
    SELECT riderId, rideDistance, rideDate
    FROM mileageLog
    WHERE rideDistance > 99
    </cfquery>
    and my results would be something like
    Kevin 114
    Chris 103
    Kevin 100
    Don 102
    Kevin 106
    Now how can I get the count for each person
    Kevin 3
    Chris 1
    Don 1

    jkgiven wrote:
    > I appreciate your help
    >
    > taking a look at your suggestion, the >99 part needs
    to refer to the
    > rideDistance column (the 114, 103, 100, 102, 106) thus
    the greater than 99
    > amounts. And how would I refer to each rider count total
    (Kevin 3, Chris 1, Don
    > 1)
    >
    > I reworked the quety to this... but still no go
    > SELECT riderId, count(riderId) AS riderCount,
    rideDistance
    > FROM mileageLog
    > GROUP By riderId
    > HAVING rideDistance >99
    >
    > It tells me that rideDistance is not part of an
    aggregate function. I thought
    > to get around this I just had to have each variable
    called for in the SELECT
    > line?
    >
    in the SELECT statement change rideDistance to
    SUM(rideDistance) - i
    think that is what you want to get anyway, isn't it? - and
    you won't get
    that error. it's not the SELECT statement you have to have
    the vars
    listed in; it's either in the GROUP BY or use an aggregate
    function on it..
    Azadi Saryev
    Sabai-dee.com
    Vientiane, Laos
    http://www.sabai-dee.com

  • How to get this output using sql query?

    Hi,
      How to get this output using sql query?
    Sno Name Age ADD Result
    1 Anil 23 delhi Pass
    2 Shruti 25 bangalor Pass
    3 Arun 21 delhi fail
    4 Sonu 23 pune Pass
    5 Roji 26 hydrabad fail
    6 Anil 28 delhi pass
    Output
    Sno Name Age ADD Result
    1 Anil 23 delhi pass
    28 delhi pass

    Hi Vamshi,
    Your query is not pretty clear.
    write the select query using Name = 'ANIL' in where condition and display the ouput using Control-break statements.
    Regards,
    Kannan

  • How to get this script to work with different browser

    Do you guys know how to get this script to work with mozilla firefox? 
    do shell script "open -a safari 'https://login.binck.nl/klanten/Login.aspx?ReturnUrl=%2fklanten%2fdefault.aspx'"
    tell application "Safari"
      activate
              tell document 1
                        repeat until ((do JavaScript "location.host") is "login.binck.nl")
                                  delay 1
                        end repeat
      do JavaScript"document.getElementById('ctl00_Content_Gebruikersnaam').value='sim';document.ge tElementById('ctl00_Content_Wachtwoord').value='password';window.open(document. g etElementById('ctl00_Content_LoginButton').href, '_self', 'true');"
              end tell
    end tell
    Thank you so much in advance:)

    That isn't possible. Firefox's AppleScript dictionary doesn't contain anything which can be used to manage JavaScripts.
    (63741)

  • How to get key from MDX Query

    Hi All,
    how to get key from mdx query ?
    example :
    SELECT [Measures].[67822GFASOU7KUT6FKHSQ34FV] ON COLUMNS NON EMPTY CROSSJOIN([ZCOMPANY].MEMBERS, [ZMILL].MEMBERS) ON ROWS FROM ZODS_GL/ZODS_GL_001
    the result from this mdx query are zcompany text and zmill text, how to get company key and mill key ?
    Regards
    JeiMing

    hi Jeiming,
    to get key in mdx, you can try something like
    [ZCOMPANY].[LEVEL01].MEMBERS
    properties [ZCOMPANY].[2ZCOMPANY]
    following threads may useful
    Extracting texts with MDX
    MDX Statement - display only keys for characterstics and their dis. attrib.
    hope this helps.

  • Single report with multiple queries OR multiple reports with single query

    Hello Experts,
    I have a confusion regarding Live Office connection for many days. I asked many people but did not get a concrete answer. I am re-posting this question here and expecting an answer this time.
    The product versions that I am using are as follows:
    FrontEnd:
      BOE XI 3.1 SP4 FP 4.1
      Xcelsius Enterprise 2008 SP4
    Backend:
      SAP BW 7.0 EHP1
    I have created a dashboard which is getting data from a webi report using LO connections.
    The webi report has five report parts which are populated by five different queries.
    Now my question is, when the five LO connections are refreshed, is the webi report refreshed five times or just once?
    If the report is refreshed five times, then I guess it is better to have five different webi reports containing single report part, because in that way we can prevent same query being executed multiple times.
    SO what is the best practice- to have a single report having multiple queries - OR - to create multiple webi reports with single query?
    Thanks and Regards,
    PASG

    HI
    I think Best Practice is Multiple reports with single query
    Any way If LO connections refresh 5 time the query will refresh 5 timesRegards
    Venkat

  • INSERTED Table - When it gets populated with single or multiple rows?

    Hi,
    I'm trying to create a trigger which then insert to a table. i'm wondering when does the INSERTED table gets populated with single or multiple rows?
    Should I always assume that the INSERTED Table will contains several rows? What does the scope of the INSERTED table in the trigger, isn't based on the user session?
     The reason why i asked this is because as far as i know inserted table may contain several table when the trigger fires which is why I use cursor to insert  records in the table ( there's a behind why i use cursor).
    But if the inserted table will only contain a single record during the session of the trigger then i can avoid the cursor.
    Thanks.

    But since we control the transaction process and we know for a fact that user will only be able to save a record one at a time, do we still expect multiple rows? I just want to have a clear concept on the INSERTED table.
    ...and then the DBA or someone else sees fit to enter a number of rows directly from a query window. And don't laugh. That is bound to happen sooner or later.
    However, just because this can (and will) happen does not mean that you need to handle it on equal footing with the normal case user entering data through the application. What you cannot permit yourself to is to drop the DBA case on the floor, that is write
    the trigger as if there would either be single-row inserts and produce incorrect results for multi-row inserts.
    But, yes, allowing yourself to use a cursor, if you want to reuse the existing stored procedure is feasible. That is also the more drastic solution suggested by Tom to add an explicit check that disallows multi-row inserts.
    Finally, permit me to comment on this:
    Additionally, it's  difficult to use the code below as i need to pass the identity id of tbl_A to tbl_B
    You can use the OUTPUT clause to capture the values, but that requires that you have something you can map the identity values to in the columns you insert, and this is not always the case. However, there is a lot simpler solution to the problem: don't
    use IDENTITY. IDENTITY is one of these over-used and over-abused features in SQL Server. You need it when you want to support high-concurrency inserts, because rolling your own requires a serialisation point. But with a moderate insertion frequency, IDENTITY
    only gives you headache.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • In Table Control How to get only a single row .

    Hi
    In Table Control How to get only a single row .I am able to decrease it its height to 4 but then 2 rows is getting dsplayed .I want only one row to be display and 2nd row should be deactivated or not visible.
    regards
    Avik
    Edited by: Julius Bussche on Jan 30, 2009 1:10 PM
    Removed friendly greeting from the subject title

    Hi Avik
    use this code it will help you.
    MODULE passdata OUTPUT.
      READ TABLE it_revision INTO wa_rev INDEX tab_clc-current_line.
      IF sy-subrc = 0.
        LOOP AT SCREEN.
          IF screen-group1 = '111'.      " 111 IS THE GROUP NAME
            screen-input = 1.          " input mode
            screen-active = 1.         " input mode.
            MODIFY SCREEN.
          ENDIF.
        ENDLOOP.
      ELSE.
        LOOP AT SCREEN.
          IF screen-group1 = '111'.       "GROUP NAME
            screen-input = 0.           " display mode
            screen-active = 1.          " DISPLAY MODE.
            MODIFY SCREEN.
          ENDIF.
        ENDLOOP.
      ENDIF.
    ENDMODULE.                 " PASSDATA  OUTPUT
    Make sure in group tou are passing the field name that you want in input mode on the base of other field
    Hope it will help you.
    Thanks
    Arun Kayal.

  • How to do this with message mapping in PI  ?

    Hi All,
    Field 1 = 100 characters having values in  first fifty characters and last 50 characters blank . I need to remove all the first 50 characters with blank and pass 100 blank characters .How to do this with message mapping
    Thanks

    Adding to that, since usually a tab = 8 spaces. What you can do is to open notepad, press tab 4 times. Copy it and paste 3 times, afterwards press space 4 more times and you get 100 spaces.
    Regards,
    Mark

  • How to get rozetta with lion?

    how to get rozetta with lion?
    I have put all of Snow Leopard on an external drive (checked to include Rozetta)
    but when I try to use it to start up my computer with Lion installed - it calls this external drive "Recover Drive" and
    it asks me to select from 5 options - all of which sound ominous

    gk5198 wrote:
    I have never used rpm files but Zipeg says it will open them - Zipeg.com
    I'm not really looking for decompressing the rpm, I'm looking for the other features like actually installing the rpm in place. There are a lot of utilities that would just "unzip" the rpm like Unarchiver, etc, but I'm looking for something that will do the rpm install...
    -Thanks

  • SqlServer 2008 Database Status Showing(Recovery pending)..How to get this database in online?

    SqlServer 2008 Database Status Showing(Recovery pending)
    How to get this database in online?
    This is SharePoint Content database.
    Badri

    SqlServer 2008 Database Status Showing(Recovery pending)
    How to get this database in online?
    This is SharePoint Content database.
    Badri
    Hi,
    Please try running below in master database
    restore database db_name with recovery
    Chances are that this command would not succeed because I guess there was corruption in database and you restarted SQL Server service. Or can you please tell how your database went into recovery pending state.
    Please check SQL Server errorlog you would find information regarding this change. Please post relevant log information here. Please check event viewer as well
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it.
    My TechNet Wiki Articles

  • How to get this skin effect on a black model?

    hello everyone!!!
    i was wondering if anyone knows how to get this final effect on a picture with a black model?

    1. Original image
    2. Convert to grayscale, then back to RGB
    3. Approximate color of sample
    4. Curves to add contrast
    Final.  Dodge selected quartertones
    If desired, add a very, very slight noise. Not in image here. (Add'l layer: Gaussian, Mono, very low opacity)

  • How to get this information for Conky

    Hi people,
    My question is how to get this information for show in Conky:
    - KDE version.
    - Last sync (pacman -Sy) and Last update (pacman -Su)
    For the first point could be use a script that execute $ kdesu --version and get information from there.
    I have no idea how get information from pacman (may be logs?).
    Any ideas?
    Thank you.

    I have had tremendous success with LUA in Conky on Arch. And all you need to to is put the text HI after the "TEXT" line. ^^;
    Examples of my LUA usage:
    http://fc02.deviantart.net/fs71/i/2010/ … usLink.png
    http://kittykatt.silverirc.com/screens/conky-HUD.png
    EDIT:  Also, I've had success with getting the KDE version by doing the following...
    kwin --version | awk '/^Qt/ {data="Qt v" $2};/^KDE/ {data=$2 " (" data ")"};END{print data}'
    This is the method I'm currently using in screenFetch. Tested it a couple of times myself, but besides that, I'm not sure if it will work or not.
    Last edited by kittykatt (2010-04-22 17:52:25)

Maybe you are looking for

  • Setting current values in Multiple Select List in SQL Query based Report

    Hi, I have a report based on a sql query that contains a multiple select list. Unfortunately I cannot get the multiple select list to display the current values (p_value) correctly. I have created a page item, :p311_current_versions, that is set usin

  • Where to set up a TYPE-POOL Declaration in a Function Group ?

    Hi, I ve got a Function Group. I set up a Function Module in the Function Group. I must use  TABLES I_T_SELECT TYPE SBIWA_T_SELECT. I get the error: Type pool SBIWA has not been declared Message no. FL031 Diagnosis You used a type from type pool & in

  • Unable to connect to the server - windows sockets

    //////socket connector method//// bool SocketConnecter::connect(const std::string& ip, size_t port) size_t uport = htons(port); std::string sPort = toString(uport); // Resolve the server address and port const char* pTemp = ip.c_str(); iResult = geta

  • Session Bean ejbCreate( parm ) Does Not Work in App Server 8  2005 Q2 Editi

    I have the following in my session bean: public class aauthfacadeBean implements SessionBean { public void ejbCreate() throws CreateException { public void ejbCreate( boolean logActivity, String dbCodedNameAauth, String uname, String pswd ) throws Cr

  • Reciprocal Graph Scales

    I'm trying to plot an XY Graph with one of the scales (x-axis) set to the reciprocal of a variable.  I can plot this by calculating the values within an array, however the scales (as would be expected) now show the reciprocated value (ie. 1/value).