How to write the following SQL

I have a table with the following columns seq_no, customer_no, sales_person, card_type, NTB_Cust, paid_flag. He basically tells what a person sale that sold the customer what card, and if the customer is a New_To_Bank. Seq_no field is a sequence running. I need fill out the paid_flag as 1 or 0 according to certain rules.

The first point to consider is that the card_type should be "PREFERRED" and NTB_Cust = "NTB".
Then, if the sales_person has sold two cards that follow with the above criteria, in the same customer_no, then only the first will be marked with paid_flag = 1. If he sold 3 consecutive to the same customer cards, then the 1st and the 3rd will be marked as paid_flag = 1. If the sales_person has sold 4 cards to the same customer and then the 1st and the 3rd will be marked as paid_flag = 1. And so on.

See below the expected value of paid_flag
seq_no card_type NTB_Cust paid_flag customer_no sales_person
XXX 999 FAVORITE NTB 1 1
2 999 FAVORITE NTB XXX 0
XXX 3 999 FAVORITE NTB 1
4 999 PRESTIGE NTB XXX 0
XXX 5 888 FAVORITE NTB 1
XXX 6 888 FAVORITE OLD 0
7 FAVORITE NTB 888 XXX 1

Hello

Try

WITH T1
AS
(
SELECT 1 seq_no, 'XXX' sales_person, 999 customer_no, 'PREFERED' card_type, 'NTB' NTB_Cust, 1 paid_flag FROM DUAL UNION ALL
SELECT 2, 'XXX', 999, 'PREFERED', 'NTB', 0 FROM DUAL UNION ALL
SELECT 3, 'XXX', 999, 'PREFERED', 'NTB', 1 FROM DUAL UNION ALL
SELECT 4, 'XXX', 999, 'PRESTIGE', 'NTB', 0 FROM DUAL UNION ALL
SELECT 5, 'XXX', 888, 'PREFERED', 'NTB', 1 FROM DUAL UNION ALL
SELECT 6, 'XXX', 888, 'PREFERED', 'OLD', 0 FROM DUAL UNION ALL
SELECT 7, 'XXX', 888, 'PREFERED', 'NTB', 1 FROM DUAL )
SELECT T1.*, CASE WHEN MOD(ROW_NUMBER() OVER (PARTITION BY customer_no, card_type  ORDER BY SEQ_NO),2)=1 AND CARD_TYPE = 'PREFERED'
         AND NTB_Cust='NTB' THEN 1 ELSE 0 END PAID_FLG_FROM_SQL
FROM   T1
ORDER BY SEQ_NO;

* 009 *.

Tags: Database

Similar Questions

  • How to write the following UPDATE query

    I have a table with data as below:

    Subscriber IMSI imsi_rank
    1123211
    123123412
    13324423
    13424
    15
    2232131
    2123212
    2123123
    24
    25

    Now, the data is dense and continuous for a SUBSRCIBER. Between there is no value for a SUBSCRIBER's IMSI null. However, where one or more IMSI is null, I need to update the table to move the IMSI values to the top of the IMSI_RANK.

    Say for example for Subscriber 1, IMSI value 2312341 and 332442 is set to NULL value. So I need to write an application Update or PLSQL that will update the data as below.

    Subscriber IMSI imsi_rank
    1123211
    13422
    13
    14
    15
    2232131
    2123212
    2123123
    24
    25

    I use 11g.

    You cannot perform SQL on any PL/SQL collection type. You need to loop through them and make the change.

  • Open XML, how to write the path

    Hello

    I'm new to the Blackberry development and I hope you can help me with my problem. I try to work with an XML file, and so far, all that does very well as long I had the xml file, I work on, in the folder of my java application and deyployed using the desktop software. Now, I tried to put the file somewhere else on the Blackberry and I don't know how wirte the path to the source code. I tried the following, but it seems to be bad:

    private static String _xmlFileName = "file:///store/home/user/documents/test.xml";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                InputStream inputStream = getClass().getResourceAsStream( _xmlFileName );
                Document document = builder.parse( inputStream );
    

    I hope you can give me a hint, how I write the correct path?

    Thank you very much!

    Best regards, jtr87

    PS: Sorry for my bad English, but I did not use it very often.

    You need to do something like that to get your InputStream:

    /** * @return an open InputStream for a file, or null if file does not * exist. * @throws IOException if there is an error opening the file */InputStream getInputStream(String name) throws IOException {
        FileConnection fc = null;
        try {
            fc = (FileConnection) Connector.open(name, Connector.READ);
            if (fc.exists()) {
                return fc.openInputStream();
            }
        } finally {
            if (fc != null) {
                try {
                    fc.close();
                } catch (Exception ignored) {
                }
            }
        }
        return null;
    }
    

    Notice that you must close the FileConnection at some point, regardless of if the call to openInputStream worked.

  • a disk error has occurred while trying to write the following file

    I was working on my video and I put in a video file and a 10 seconds later, I get an error saying "a disk error occurred while trying to write the following file.

    and audio of the video was not working I close Premiere Pro and open again to do the same thing and it happens again if you know how to fix this please tell me I need to change my video so I can get it to the top on youtube tomorrow.Help pls.png

    I contacted support and it turns off everything, I had to do was move the first clip on the desktop... lol Thanks much for the great help! Sorry for the trouble

  • How to write the query

    Hello

    How to write the sql query

    I have three type of table as

    1 table emp

    EMP_ID FIRST_NAME DEPT_ID

    ---------- -------------------- ----------

    1 kumar 10

    2 sam                          20

    3 30 damu

    2 table dept

    EMP_ID SALE_ID DEPT_ID

    ---------- ---------- ----------

    1 101 10

    2 102 20

    3 103 30

    3. table sale

    EMP_ID SALE_ID SALE_AMT

    ---------- ---------- ----------

    1 101 7

    2 102 8

    3 103 9

    I want the result as

    EMP_ID DEPT_ID SALE_AMT

    -------      ---------   -            --------

    1                10                  7

    Thank you

    Are you looking for this?

    SELECT T1. EMP_ID,

    T1. DEPT_ID,

    W3M SALE_AMT

    FROM EMP T1,

    SALE T3

    WHERE T1. EMP_ID = T3. EMP_ID;

    OUTPUT:

    EMP_ID DEPT_ID SALE_AMT

    ------- ---------- ----------

    1         10          7

    2         20          8

    3         30          9

    If this is not the case, after the actual output, you need. Because that gives you the amount of sales deptwise

  • How to write the select query for it

    Hello

    I had an html form and the area I drop down and he needs to select several values in the drop-down box. When I select multiple values then I have to write the query to SQL select statement.

    When I try to write the select statement and trying to run I get the error message.

    Select * from Table

    where emo_no = '1,2,3 '.

    That's how I write the query please suggest me how to write the query to select several values in the drop-down box.

    Thank you

    Use the keyword sql 'in '.  If you don't know how, I've heard good things about the book Teach Yourself SQL in 10 Minutes by Ben Forta.

  • How to write the script in FDMEE below.

    How to write the script in FDMEE below.

    Script below is the FDM Script.How write in FDMEE.

    If (varValues (14) '113101' =) OR (varValues (14) '113201' =) OR (varValues (14) '113301' =) OR (varValues (14) = "252111") OR (varValues (14) '156101' =) then

    Result = "21_asd."

    Please help me on this issue.

    Kind regards

    Satheesh, S

    If you want to determine the id of the target account your opening assignment statement must be:

    Account = fdmRow.getString ("ACCOUNTX")

    As if - elif-instructions else keep lowercase stream operators. If you continue a command on multiple lines, then place parentheses is

    If (account == "113101") or (account == "113201") or (account == "113301") or (account == "113401") or (account == "113501") or (account == "113601") or (account == "215101") or (account == "215201") or (account == "215301") or (account == "215401") or (account == "215501") or (account == "215601") or (account == "252111") or (account == "156101"):

    fdmResult = "21_ADNIP".

    should be (also get rid of the unnecessary parentheses)

    If (account is "113101" account is "113201" or account is '113301' account is "113401" or account is "113501" or account is "113601" or account is "215101" or account is "215201" or account is "215301" or account is "215401" or account is "215501" or account is "215601" or account is "252111" or account is "156101"):

    fdmResult = "21_ADNIP".

  • How to write the even-odd fill feature?

    How to write the even-odd fill feature?

    Maybe like this:

    app.executeMenuCommand ('* ');

    01.jpg

    There is a command in the PathItem object named evenodd. I think that if you change the property of evenodd and get a member of a composite path path, you can achieve a desired result.

  • How to write the 'C' alpabelt within a circle of author?

    Hello

    How to write the symbol of copyright on first Pro CC (ie the alpabelt 'C' inside a circle) ?

    Thank you

    On a Mac, Option + G.

    MtD

  • How to write the query option in expdp

    Hi Please someone help me how to write the query option in expdp... .in expdp using the query option...

    where AM columnname between 5 May 12 02:57:00.000' and ' 02:59:59.999 6 May 12: ';


    Please do what is necessary...

    Pavan Kumar says:
    QUERY = (columnname scott.test: "where between 5 May 12 02:57:00.000 h ' and ' 6 May 12 AM 02:59:59.999'")

    Who will fail in databases, because you assume nls_date_format. How it is difficult to put to_date() surround channels? Rather than play with quotation marks, using one parfile thusly.

    query=table_owner.table_1:"where business_date between to_date('20120505025700 am','yyyymmddhhmiss am') and to_date('20120505025959 am','yyyymmddhhmiss am')"
    query=table_owner.table_2:"where business_date between to_date('20120505025700 am','yyyymmddhhmiss am') and to_date('20120505025959 am','yyyymmddhhmiss am')"
    query=table_owner.table_3:"where business_date between to_date('20120505025700 am','yyyymmddhhmiss am') and to_date('20120505025959 am','yyyymmddhhmiss am')"
    

    You do not have to have all the clauses in a single line, as they are side by side parfile, which would be enough. For this reason parfile is better than the command line in order to avoid all the back-citing dance.

  • How to convert the following code in as3?

    As the title says... How to convert the following code to as3?... Thanks in advance.

    import flash.display.BitmapData;

    linkageId = "landscape";
    myBitmapData = BitmapData.loadBitmap (linkageId);


    MC = this.createEmptyMovieClip ("mc", 1);
    mc.attachBitmap (myBitmapData, 1);

    onMouseMove = function() {}
    myNewColor = "0 x" + myBitmapData.getPixel(_xmouse,_ymouse).toString (16);
    newColor.setRGB (myNewColor);
    selectedColor.colorValue.text = myNewColor;
    }
    selectedColor.swapDepths (_root.getNextHighestDepth ());
    newColor = new Color (selectedColor.sample);

    :

    var myBitmapData:landscape = new landscape (0,0);

    var bmp:Bitmap = new Bitmap (myBitmapData);
    addChild (bmp);

    stage.addEventListener (MouseEvent.MOUSE_MOVE, f);

    function f(e:MouseEvent):void {}
    var myNewColor:String = "0 x" + myBitmapData.getPixel(mouseX,mouseY).toString (16);
    newColorTransform.color = uint (myNewColor);
    selectedColor.sample.transform.colorTransform = newColorTransform;
    selectedColor.colorValue.text = myNewColor;
    }
    addChild (selectedColor);
    var newColorTransform:ColorTransform = selectedColor.sample.transform.colorTransform;

  • How to write the text file in Shockwave?

    Someone knows how to write the text file in Shockwave on the disc of the user?

    Thanks in advance.

    These Xtras can cause a lot of havoc when used with the intent to hurt.
    What you can do is to write with setpref and store a list of backups and the
    registers itself separately. Next, you need to build your own save/open
    dialog box for the user:
    * Choose a previously saved file to load or replace
    to create a user type the name of a new file to be saved.

    The only thing that remains is that the user can't decide where files
    are saved.

    Manno

    SiuLinda wrote:
    > Thanks a lot for your answer.
    > Yes, cookies is good, but I have to write a program to save the text file in
    > When the user wants, the user can open these files later if they like as, using
    > Filextra and Fileio, but I found that all these Xtra extensions seem to be not supported by
    > shockwave.
    >

    --
    ----------
    Manno Bult
    [email protected]

  • Best way to write the Pl/Sql

    Hi all
    Can someone say best written below stored proc:

    procedure missing_authorized_services is
    v_truncate_sql varchar2 (200);
    v_sql varchar2 (2000);
    BEGIN
    v_truncate_sql: = "truncate table missing_authorized_services;
    immediately run v_truncate_sql;
    commit;

    v_sql: = "INSERT into missing_authorized_services select distinct trim (service_group_Cd) as service_group_Cd, trim (service_cd) as stage_1_mg_service_request service_cd
    where (service_group_cd, service_cd) not in)
    Select distinct service_group_cd, stage_3_servcd_servgrp_dim service_cd)';

    immediately run v_sql;
    commit;

    END missing_authorized_services;


    / * I do select the table and then try to insert into another table the result set * /.

    Please help,
    Thank you
    J

    Hello

    The best way to write the PL/SQL (or any code) is by small steps.
    Start with a very simple procedure that does something (anything), just enough to make sure it works.
    Add a lot of statements of output so you can see what made the procedure. Don't forget to delete them after that trial is over.

    For example:

    CREATE OR REPLACE procedure missing_authorized_services IS
            v_truncate_sql  VARCHAR2 (200);
    BEGIN
         v_truncate_sql := 'truncate table missing_authorized_services';
         dbms_output.put_line (  v_truncate_sql
                        || ' = v_truncate_sql inside missing_authorized_services'
                        );
    END      missing_authorized_services;
    

    If you get any errors (for example, ORA-00955, because you try to give the same name to a procedure that you already use for a table), then fix the error and try again.
    When he worls perfectly, then add another baby step. For example, you can add the line

    EXECUTE IMMEDIATE v_truncate_sql;
    

    and test again.

    Do not use SQL dynamic (EXECUTE IMMEDIATE) unless you have to.
    Is there a reason to use dynamic SQL for INSERT statements?

  • How to explain the following code?

    How to explain the following code?
    1 set setOpenTradeIds = mapTrades.keySet (filter);
    2 map mapResults = null agent, map.invokeAll ((Filter));
    Is defined a class and setOPenTradeIds a new object?
    Is card calss and mapResults a new object?

    Thank you

    Published by: frank.qian on June 7, 2009 10:48

    Hi Frank,.

    Is mapTrades an object and a set of keys one of its methods?

    mapTrade is a reference variable refers to an instance of a class that implements the keySet() method that returns a reference to an instance of a class that implements the interface of game

    What is map.invokeAll? Where to get the information about it?

    map is a reference variable refers to an instance of a class that implements the invokeAll() method that returns a reference to an instance of a class that implements the map interface In case of card to make reference to an instance of a class that implements the InvocableMap interface, you can find consistency documentation 3.4.2 method to InvocableMap.

    Kind regards

    Harv

  • How to write the SQL without using dynamic SQL?

    How can you write this under SQL without using execute immediately?

    You can use static SQL (using something like a CASE statement)?

    test procedure (one in varchar2, b number, each number) is

    v_num_recs pls_integer;

    Start

    Select count (*)

    in v_num

    FROM table1

    where

    col1 = one and

    If b is not null then col2 = b

    If c is not null then col3 = c;

    / * i.e. If b is not null, where condition to add this line only. If c is not null, where condition should add only this line. OR condition No. it * /.

    dbms_output.put_line (v_num);

    end;

    Or should I use dynamic SQL statements for this?

    I was wondering if the two are NOT NULL? Well check this.

    Select count (*) in v_num

    table

    where col1 = one

    and col2 = (CASE WHEN (b is not null) THEN b ELSE END col2)

    and col3 = (CASE WHEN (c is not null) THEN ELSE END col3 c)

Maybe you are looking for

  • Reinstall Windows XP SP3

    I recently reinstalled Windows XP SP3. Reinstallation was successful, however, I think having acquired a "drive F" that I didn't have before. This disc is only 3.14 GB. All downloads (for example. Microsoft Office) seem to default to this disk and th

  • Windows XL do not recognise my Hitachi camcorder

    I haven't used my Hitachi camcorder for 2011 and now find my Acer computer no longer recognizes my dvd camcorder so I'm unable to download movies, I want to change my Windows Movie Maker program.  I was editing and burning to disc in this program bef

  • RECVD MESSAGE ' OUTLOOK EXPRESS DOES NOT.

    Have a lot of emails after hospitalization - received message "outlook express not responding not" computer crashes if you try to click on anything whatsoever

  • How to run 2 hard drives striped

    I have 2 identical hard drives and tries to run them in a striped mode, but when I go into disk management there are three options I simple striped and mirrored but scratched him and the mirror are grayed out. can not run two hard drives in a striped

  • Arrears of vista SP2 update daily to install

    Every day I get a notification to install SP2 for vista, I accept it, I get a note that the installation was successful, but the notification is displayed again the next day. (SP1 is already installed)