SQL Sub-Query Help

Hi,
1. In the query below, How to display FirstActNum to the User( which is inner select decode statement ) ?
SELECT A.One, A.Two, A.Three, A.Four from
(Select FL.first_act_num as One,FL.move_num as Two, SUM (FL.payment) as Three,SUM(FL.next_amount) as Four from FirstLib FL
where FL.act_num IN (
Select
DECODE(l.first_act_num,'0000000',l.act_num,l.first_act_num) as FirstActNum
from FirstLib L, ManageAccount A
WHERE
L.act_id=A.act_id
AND A.id='123456789')
group by FL.primary_acct_num,FL.loan_num) A,OtherTable B
where A.One = B.first_act_num AND A.Two = B.move_num;
2. Is there any other better way to write these kind of queries?
Thanks

Sundar,
No, its different.. I am just comparing with that field.
The data looks like..
ACT_NUM      FIRST_ACT_NUM
11111          11111
22222          11111
33333          11111
In some cases FIRST_ACT_NUM is not populated (i.e it will have 0000000), in this case I am using ACT_NUM
ACT_NUM      FIRST_ACT_NUMM
55555          0000000
87878          0000000
90909          0000000

Similar Messages

  • Oracle 8i - PL/SQL sub query not working in PROC, but works ins SQL

    I have read about certain things not working in 8i and I think this is one of them, but I was wondering if anyone had a work around. In the place of the SELECT SYSDATE FROM DUAL, I have a table look up, where I am going to look up the OCN of the corresponding VENDOR_ID ( a column in the original query ). I am doing it in a decode statement because if the first condition in the decode statement is met, that's it. But if not, it needs to look up the OCN number in this other table. Simple enough, conceptually. I thought of a view but that necessitates a SELECT statement, too. Anyway, here is the code with the appropriate text bolded:
    CREATE OR REPLACE PROCEDURE tstINS_RATE_ROUTE_RECORDS_PROC (GET_CUR_PERIOD IN DATE) IS
         CUR_PERIOD DATE;
         BEGIN
         CUR_PERIOD := GET_CUR_PERIOD;
         Insert into RATE_ROUTE (
           CVBI_KEY
         , VENDOR_ID
         , OCN
         , ST_CD
         , PERIOD
         , MDFY_DT )
         Select
           C.CVBI_KEY
         , C.VENDOR_ID
         <b>, decode( c.send_lca, 'YES', 'XXX', (SELECT SYSDATE FROM DUAL) )</b>
         , decode( c.send_lca, 'YES', 'XX', SUBSTR(C.ZLOC,5,2) )
         , CUR_PERIOD
         , TO_CHAR(SYSDATE)
         FROM
           rpt_ds1_cnt_cat c
         , cogs_resource cr
         , cogs_t1activity ct1
         , rpt_ds1_aloc_zloc_reverse_vw az
         where (C.CVBI_KEY = CR.CVBI_KEY (+)
         and  CR.PERIOD = CUR_PERIOD)
         AND  (C.CVBI_KEY = CT1.CVBI_KEY (+)
         and CT1.PERIOD = CUR_PERIOD)
         and (az.master_route_name=c.aloc||'-'||c.zloc OR az.reversed=c.aloc||'-'||c.zloc)
         END; -- INS_RATE_ROUTE_RECORDS_PROC

    have read about certain things not working in 8i and I think this is one of them,Yes as I said scalar sub-queries were also not recognized within PL/SQL in 8i.
    Re: PLS-00103: Encountered the symbol "SELECT" when expecting one of the fo
    I was wondering if anyone had a work around.Write a function that returns the value. You may incur a performance penalty from a context switch to PL/SQL, but it may be balanced by the decode optimization you are attempting.

  • SQL select query help

    I know this is a SQL question but I can't seem to figure this
    out. The below SQL query will run without error however it will
    output the company_name for every row which I dont want.
    So basicly it currently outputs like this now:
    company_name - apple
    company_name - dell
    BUT want it to output like this:
    company_name - apple,dell
    MY CURRENT QUERY:
    SELECT d.disputeid, t.company_name, t.tlid, t.type,
    l.description
    FROM member_disputes d, member_tradeline t, letters l
    WHERE d.fk_tlid = t.tlid
    AND d.fk_letterid = l.letterid
    AND d.fk_memberid = #GetAuthUser()#
    Any help much appreciated

    quote:
    Originally posted by:
    LionelR
    I know this is a SQL question but I can't seem to figure this
    out. The below SQL query will run without error however it will
    output the company_name for every row which I dont want.
    So basicly it currently outputs like this now:
    company_name - apple
    company_name - dell
    BUT want it to output like this:
    company_name - apple,dell
    MY CURRENT QUERY:
    SELECT d.disputeid, t.company_name, t.tlid, t.type,
    l.description
    FROM member_disputes d, member_tradeline t, letters l
    WHERE d.fk_tlid = t.tlid
    AND d.fk_letterid = l.letterid
    AND d.fk_memberid = #GetAuthUser()#
    Any help much appreciated
    Suddenly a light bulb illuminated over my head.
    <cfouput>
    company_name - #ValueList(yourquery.company_name)#
    </cfoutput>
    If that doesn't work, either change this, "t.company_name" to
    "company_name" or "t.company_name as company_name".
    I can't believe none of us thought of this earlier.

  • SQL SELECT Query Help   ..Please its very Urgent!!

    Hi All,
    I am having Oracle Database whice is storing 1000's of records daily.
    I need to select some information based on date and time.
    I am having two coloumns for Date and time. The first column(testDate) of type Date stores date as MM/DD/YY format and the second column(testTime)of type Numeric stores the time in seconds.
    The Example data is :
    testDate ------=-- testTime
    11/12/2002 --- 35000
    11/12/2002 --- 43000
    11/12/2002 --- 45000
    11/12/2002 --- 75000
    11/13/2002 --- 2000
    11/13/2002 --- 3500
    11/13/2002 --- 4300
    11/13/2002 --- 9800
    11/13/2002 --- 23000
    11/14/2002 --- 5000
    11/14/2002 --- 10000
    11/14/2002 --- 15000
    How can i write a SELECT Query to get the records of specific date and seconds to next day specific date and seconds.I mean i want all the records between 11/12/2002 --- 43000 seconds to 11/14/2002 --- 1000 seconds.
    If any one helps me in this regard iam very thank full to them.Its very urgent for me.
    Thanks

    Hi m7nra,
    I used the query as
    SELECT * FROM table
    WHERE testDate + (testTime/(24*60*60)) BETWEEN TO_DATE('MM/DD/YYYY','12.11.2002') AND TO_DATE('MM/DD/YYYY','14.11.2002')
    its giving DATE FORMAT NOT RECOGNIZED error.
    The Example data is :
    testDate ------=-- testTime
    11/12/2002 --- 35000
    11/12/2002 --- 43000
    11/12/2002 --- 45000
    11/12/2002 --- 75000
    11/13/2002 --- 2000
    11/13/2002 --- 3500
    11/13/2002 --- 4300
    11/13/2002 --- 9800
    11/13/2002 --- 23000
    11/14/2002 --- 5000
    11/14/2002 --- 10000
    11/14/2002 --- 15000
    infact i need all the records between 11/12/2002 --- 43000 seconds to 11/14/2002 --- 1000 seconds.
    Please help me to find a full query beacuse iam very new to Oracle.
    Thanks,
    S R Mannava

  • SQL pivot query help

    HUM ADG DYS (NIA, SIM, TRC, TRX) SMALL BRANDS (LUP, KAL,CRN,LPP,SYN)
    MON TUE WED THURS FRI MON TUE WED THURS FRI MON TUE WED THURS FRI MON TUE WED THURS FRI
    VENDOR
    INT
    QUAN
    STER
    LASH
    OSP
    HIB
    PROD
    I’d like to put together a query to populate the tables above,like count of recods for each vendor for each brand with the criteria for selecting within one week.
    Here vendor_cd(INT,QUAN,STER,...etc),brand_cd(HUM,ADG,NIA,SIM,..eyc).we are extracting the details from file detail table whose column are like FILE_ID,FILE_RECEIPT_TS,REC_INSERT_TS,VENDOR_CD,BRAND_CD,RECORD_COUNT.
    Edited by: ASHWINI89 on Mar 21, 2013 8:33 PM

    Welcome to the forum!!
    Please consider the following when you post a question. This would help us help you better
    1. New features keep coming in every oracle version so please provide Your Oracle DB Version to get the best possible answer.
    You can use the following query and do a copy past of the output.
    select * from v$version 2. This forum has a very good Search Feature. Please use that before posting your question. Because for most of the questions
    that are asked the answer is already there.
    3. We dont know your DB structure or How your Data is. So you need to let us know. The best way would be to give some sample data like this.
    I have the following table called sales
    with sales
    as
          select 1 sales_id, 1 prod_id, 1001 inv_num, 120 qty from dual
          union all
          select 2 sales_id, 1 prod_id, 1002 inv_num, 25 qty from dual
    select *
      from sales 4. Rather than telling what you want in words its more easier when you give your expected output.
    For example in the above sales table, I want to know the total quantity and number of invoice for each product.
    The output should look like this
    Prod_id   sum_qty   count_inv
    1         145       2 5. When ever you get an error message post the entire error message. With the Error Number, The message and the Line number.
    6. Next thing is a very important thing to remember. Please post only well formatted code. Unformatted code is very hard to read.
    Your code format gets lost when you post it in the Oracle Forum. So in order to preserve it you need to
    use the {noformat}{noformat} tags.
    The usage of the tag is like this.
    <place your code here>\
    7. If you are posting a *Performance Related Question*. Please read
       {thread:id=501834} and {thread:id=863295}.
       Following those guide will be very helpful.
    8. Please keep in mind that this is a public forum. Here No question is URGENT.
       So use of words like *URGENT* or *ASAP* (As Soon As Possible) are considered to be rude.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • SQL XML Query Help

    I have four tables and I want to create one XML file. I provided the temp tables with
    data and expected output.
    create table #ZDL(ZLN bigint, ZTLA int, ZMR decimal, ZCLS varchar(20), ZPITIP money)
    insert into #ZDL values(1234, 200000, 8.5, 'CART', 1500.00)
    create table #ZBL(ZLN bigint, ZBN varchar(50), ZFN varchar(20), ZMN varchar(8), ZLL varchar(20))
    insert into #ZBL values(1234, 'TEST Test', 'TEST', null, 'Test')
    create table #ZCC(ZLN bigint, ZSN int, ZCE int)
    insert into #ZCC values(1234, 1, 4)
    create table #ZP(ZLN bigint, ZPT varchar(50), ZPP int, ZNU int)
    insert into #ZP values(1234, 'Attached', 6500, 3)
    Expected XML Result should be:
    <TEST_DATA xmlns="http://www.TestData.com/Schema/Test"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.TestData.com/Schema/Test_Schema.xsd">
    <KEY _Name="ZID" _Value="789" _ID="ZID"/>
    <ZL>
    <ZLN>1234</ZLN>
    <ZTLA>200000</ZTLA>
    <ZMR>8.5</ZMR>
    <ZCLS>CART</ZCLS>
    <ZPITIP>1500.00</ZPITIP>
    </ZL>
    <ZBS>
    <ZB>
    <ZBN>TEST Test</ZBN>
    <ZFN>TEST</ZFN>
    <ZMN></ZMN>
    <ZLL>Test</ZLL>
    </ZB>
    </ZBS>
    <ZCC>
    <ZC>
    <ZSN>1</ZSN>
    <ZCE>4</ZCE>
    </ZC>
    </ZCC>
    <ZP>
    <ZPT>Attached</ZPT>
    <ZPP>6500</ZPP>
    <ZNU>3</ZNU>
    </ZP>
    </TEST_DATA>
    Thanks

    little change in your query as OP expected
    SELECT
    (SELECT ZLN ,
    ZTLA ,
    ZMR ,
    ZCLS,
    ZPITIP --AS [*]
    FROM #ZDL
    WHERE ZLN = z1.ZLN
    FOR XML PATH('ZL'),TYPE) AS [*],
    (SELECT
    ZBN ,--AS [*],
    ZFN ,
    ISNULL(ZMN,'') AS ZMN ,
    ZLL
    FROM #ZBL
    WHERE ZLN = z1.ZLN
    FOR XML PATH('ZB'),TYPE) AS [ZBS],
    (SELECT
    ZSN,ZCE
    FROM #ZCC
    WHERE ZLN = z1.ZLN
    FOR XML PATH('ZC'),TYPE) AS [ZCC],
    (SELECT
    ZPT,
    ZPP,
    ZNU
    FROM #ZP
    WHERE ZLN = z1.ZLN
    FOR XML PATH('ZP'),TYPE) AS [*]
    FROM (SELECT DISTINCT ZLN FROM #ZDL) z1
    FOR XML PATH('TEST_DATA')
    Nope
    it will give different output
    see the difference
    mine
    <TEST_DATA>
    <ZL>
    <ZLN>1234</ZLN>
    <ZTLA>200000</ZTLA>
    <ZMR>9</ZMR>
    <ZCLS>CART</ZCLS>
    1500.0000
    </ZL>
    <ZBS>
    <ZB>
    TEST Test
    <ZFN>TEST</ZFN>
    <ZMN />
    <ZLL>Test</ZLL>
    </ZB>
    </ZBS>
    <ZCC>
    <ZC>
    <ZSN>1</ZSN>
    <ZCE>4</ZCE>
    </ZC>
    </ZCC>
    <ZP>
    <ZPT>Attached</ZPT>
    <ZPP>6500</ZPP>
    <ZNU>3</ZNU>
    </ZP>
    </TEST_DATA>
    and see your output
    <TEST_DATA>
    <ZL>
    <ZLN>1234</ZLN>
    <ZTLA>200000</ZTLA>
    <ZMR>9</ZMR>
    <ZCLS>CART</ZCLS>
    <ZPITIP>1500.0000</ZPITIP>
    </ZL>
    <ZBS>
    <ZB>
    <ZBN>TEST Test</ZBN>
    <ZFN>TEST</ZFN>
    <ZMN />
    <ZLL>Test</ZLL>
    </ZB>
    </ZBS>
    <ZCC>
    <ZC>
    <ZSN>1</ZSN>
    <ZCE>4</ZCE>
    </ZC>
    </ZCC>
    <ZP>
    <ZPT>Attached</ZPT>
    <ZPP>6500</ZPP>
    <ZNU>3</ZNU>
    </ZP>
    </TEST_DATA>
    Its different from what Op wanted
    my suggestion gives exactly in the format wanted
    notice extra nodes ZPITIP and ZLN
    coming in your case
    Your original suggestion also has this issues
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • SQL recursive query help

    Hi All,
    I have below table
    IT_Terms_First_Date
    IT_Terms_Last_Date
    DI_Debt_Num
    IT_Terms_Seq_Num
    200501
    201101
    1000
    131
    200512
    203412
    1001
    131
    200503
    204209
    1003
    131
    200507
    201001
    1004
    131
    200510
    202710
    1005
    131
    200506
    202412
    10020
    131
    197910
    198310
    257000
    101
    198009
    202909
    298000
    101
    198101
    202908
    298000
    103
    198105
    202910
    298000
    104
    199109
    201309
    578000
    101
    199204
    201110
    600000
    101
    198009
    201010
    298010
    101
    198105
    204010
    298010
    104
    201011
    202909
    298010
    103
    I need to check whether my DI_Debt_Num having Ovelaping or not for each DI_Debt_Num,
    at this moment we are checking each row in loop and usnig function
    exec @Overlap1=[DffMonths] @ITtermsLD,@ITtermsNextFD
    exec @Overlap2=[DffMonths] @ITtermsFD,@ITtermsNextFD
    exec @Overlap3=[DffMonths] @ITtermsFD,@ITtermsNextLD
    if(@Overlap1>0 and (@Overlap2<=0 OR @Overlap3<0))
    BEGIN
    SET @CheckOverlap=1
    END
    here @ITtermsLD is the IT_Terms_Last_Date of the current DI_Debt_Num,@ITtermsNextFD is the IT_Terms_First_Date of the next row. @ITtermsFD is the IT_Terms_First_Date of the current month
    if we consider the 298000 DI_Debt_Num we have 3 IT_Terms_Seq_Num 101,103,104
    in this senario we need to check only the first 2 rows from that itself we can identify it is overlapped ,but when we consider the 298010 we need to check all 3 IT_Terms_Seq_Num 101,103,104 if we consider first two rows 101 & 103 it is not overlapped.Then
    we have to check first row with 3rd row ie 104 and it is overlapped.We are checking the overlap senario for DI_Debt_Num having multipple IT_Terms_Seq_Num rows
    Some situation first row may not be overlapped with other rows .Then we have to check the 2nd row with the next rows in the same way we are doing for first row
    My aim is to covert this looping method to a select query to improve my query performance
    Thanks in advance
    Roshan

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. You have no idea,
    do you? Temporal data should use ISO-8601 formats. You failed again! I will guess that your dates are months. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. 
    >> I have below table <<
    This is not a table! Where is the DDL?  This picture has no name. Not even a name!! There is no “seq_nbr” in RDBMS; it has to be a “<something in particular>_seq” and there are no duplicates in a sequence. 
    My guess is that each di_debt_nbr has a sequence within its range. I will call it the “foobar_seq” for lack of a name. 
    My next guess is that your dates are really months and you do not know about using a report period table. This idiom gives a name to a range of dates that is common to the entire enterprise. 
    CREATE TABLE Something_Report_Periods
    (something_report_name CHAR(10) NOT NULL PRIMARY KEY
       CHECK (something_report_name LIKE <pattern>), 
     something_report_start_date DATE NOT NULL, 
     something_report_end_date DATE NOT NULL, 
      CONSTRAINT date_ordering
        CHECK (something_report_start_date <= something_report_end_date), 
    etc);
    These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
    data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00'
    Here is another guess at what you want, if you knew what a table is: 
    CREATE TABLE DI_Debts
    (it_terms_first_date CHAR(10) NOT NULL
       REFERENCES Report_Period (month_name), 
     it_terms_last_date CHAR(10) NOT NULL
       REFERENCES Report_Period (month_name), 
     CHECK (it_terms_first_date <= it_terms_last_date), 
     di_debt_nbr INTEGER NOT NULL, 
     foobar_seq INTEGER NOT NULL, 
     PRIMARY KEY (di_debt_nbr, foobar_seq));
    INSERT INTO DI_Debts
    VALUES
    ('2005-01-00', '2011-01-00', 1000, 1), 
    ('2005-12-00', '2034-12-00', 1001, 1), 
    ('2005-03-00', '2042-09-00', 1003, 1), 
    ('2005-07-00', '2010-01-00', 1004, 1), 
    ('2005-10-00', '2027-10-00', 1005, 1), 
    ('2005-06-00', '2024-12-00', 100201, 1), 
    ('1979-10-00', '1983-10-00', 257000, 1), 
    ('1980-09-00', '2029-09-00', 2980001, 1), 
    ('1981-01-00', '2029-08-00', 298000, 1), 
    ('1981-05-00', '2029-10-00', 298000, 2), 
    ('1991-09-00', '2013-09-00', 578000, 1), 
    ('1992-04-00', '2011-10-00', 600000, 1), 
    ('1980-09-00', '2010-10-00', 298010, 1), 
    ('1981-05-00', '2040-10-00', 298010, 2), 
    ('2010-11-00', '2029-09-00', 298010, 3);
    I need to check whether my DI_Debt_nbr are overlapping or not for each DI_Debt_nbr, 
    >> at this moment we are checking each row in loop and using function 
    exec @Overlap1=[DffMonths] @IttermsLD, @ITtermsNextFD;
    exec @Overlap2=[DffMonths] @IttermsFD, @ITtermsNextFD;
    exec @Overlap3=[DffMonths] @IttermsFD, @ITtermsNextLD; <<
    And you were too rude to post the code for these functions! You write SQL with assembly language flags! We do not do that!  We also would use a CASE expression, and not IF-THEN control flow in SQL.  
    Did you know that ANSI/ISO Standard SQL has a temporal <overlaps predicate>? Notice the code to handle NULLs and the ISO half-open interval model. 
    (start_date_1 > start_date_2 
     AND NOT (start_date_1 >= end_date_2 
                AND end_date_1 >= end_date_2)) 
    OR (start_date_2 > start_date_1 
        AND NOT (start_date_2 >= end_date_1 
                 AND end_date_2 >= end_date_1)) 
    OR (start_date_1 = start_date_2 
        AND (end_date_1 <> end_date_2 OR end_date_1 = end_date_2)) 
    I tend to prefer the use of a calendar table. NULLs return an empty set, as above. 
    EXISTS 
    ((SELECT cal_date FROM Calendar 
       WHERE cal_date BETWEEN start_date_1 AND end_date_1)
     INTERSECT
     (SELECT cal_date FROM Calendar 
       WHERE cal_date BETWEEN start_date_2 AND end_date_2))
    --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

  • SQL Search Query - HELP!

    I'm trying to figure out which table/column it is that holds a particular value from the application I am using.
    I need a SQL query that will interrogate the database based on the value of a particur colunmn so that it returns and column_name that has a value called 'www.google.com' contained in it and the associated table_name
    Any ideas?
    Thanks!

    One of Michaels examples...
    michaels>  var val varchar2(5)
    michaels>  exec :val := 'as'
    PL/SQL procedure successfully completed.
    michaels>  select distinct substr (:val, 1, 11) "Searchword",
                    substr (table_name, 1, 14) "Table",
                    substr (t.column_value.getstringval (), 1, 50) "Column/Value"
               from cols,
                    table
                       (xmlsequence
                           (dbms_xmlgen.getxmltype ('select ' || column_name
                                                    || ' from ' || table_name
                                                    || ' where upper('
                                                    || column_name
                                                    || ') like upper(''%' || :val
                                                    || '%'')'
                                                   ).extract ('ROWSET/ROW/*')
                       ) t
    --        where table_name in ('EMPLOYEES', 'JOB_HISTORY', 'DEPARTMENTS')
           order by "Table"Example of it working...
    SQL> ed
    Wrote file afiedt.buf
      1  select distinct substr (table_name, 1, 14) "Table",
      2                  substr (t.column_value.getstringval (), 1, 50) "Column/Value"
      3             from cols,
      4                  table
      5                     (xmlsequence
      6                         (dbms_xmlgen.getxmltype ('select ' || column_name
      7                                                  || ' from ' || table_name
      8                                                  || ' where upper('
      9                                                  || column_name
    10                                                  || ') like upper(''%' || 'SCOTT'
    11                                                  || '%'')'
    12                                                 ).extract ('ROWSET/ROW/*')
    13                         )
    14                     ) t
    15          where table_name in ('EMP', 'DEPT')
    16*        order by "Table"
    SQL> /
    Table          Column/Value
    EMP            <ENAME>SCOTT</ENAME>
    SQL>

  • Tunning sql sub query for better performance

    I have been given the task to tune this query for better execution as presently it take a very long time execute i will appreciate if someone can help.
    Thank you.
    SELECT a.fid_trx_no, a.fid_seq_no,a.bcc_customer_account,
    a.bcc_msid,a.fid_trx_date,a.fid_trx_type,
    a.fid_trx_initial_amount,a.fid_trx_fidodollar_amount
    FROM
    SPOT.SPOT_FIDODOLLAR_TRX a
    WHERE
    a.fid_trx_status = 'PE' AND a.fid_seq_no =
    (SELECT MAX(c.fid_seq_no) FROM SPOT.SPOT_FIDODOLLAR_TRX c WHERE c.fid_trx_no = a.fid_trx_no) AND
    a.FID_TRX_DATE <
         (SELECT MAX(b.FID_TRX_DATE) FROM SPOT.SPOT_FIDODOLLAR_TRX b wHERE
         b.bcc_customer_account = a.bcc_customer_account AND fid_trx_type IN
         (SELECT par_code FROM SPOT.spot_parameter where par_value=:vAccountType AND par_type='FC')
         )

    Rob...
    so many times you post this link.. i think that Oracle should put this link in an obvious place....!!!
    Greetings,
    Sim

  • SQL Join query help

    Hello,
    I have two select statements as
    Query 1 : Select col1,col2,col3,col4,value_a from table_1
    Query 2: Select col1,col2,col3,col4,value_b from table_2
    I want to join these two select statement to get below result.
    col1 col2 col3 col4 value_a value_b
    Scenario 1: Both query fecth the result
    Result of query 1:
    Col1 Col 2 Col3 Col4 Value_a
    1 TK TL TM 100
    Result of query 2:
    Col1 Col 2 Col3 Col4 Value_b
    1 TK TL TM 200
    Ultimate join result should be
    Col1 Col 2 Col3 Col4 Value_a value_b
    1 TK TL TM 100 200
    Scenario 2: Only query 1 fetches the result
    Result of query 1:
    Col1 Col 2 Col3 Col4 Value_a
    1 TN TO TP 300
    Result of query 2:
    Col1 Col 2 Col3 Col4 Value_b
    Ultimate join result should be
    Col1 Col 2 Col3 Col4 Value_a value_b
    1 TN TO TP 300 0
    Scenario 3: Only query 2 fetches the result
    Result of query 1:
    Col1 Col 2 Col3 Col4 Value_a
    Result of query 2:
    Col1 Col 2 Col3 Col4 Value_b
    1 TN TO TP 300
    Ultimate join result should be
    Col1 Col 2 Col3 Col4 Value_a value_b
    1 TN TO TP 0 300
    How should I join these?

    Because you want a FULL OUTER JOIN .
    select
       t1.*, t2.*
    from
       table_1 t1
       full outer join table_2 t2
    on
             t2.col1 = t1.col1
       and   t2.col2 = t1.col2
       and   t2.col3 = t1.col3
       and   t2.col4 = t1.col4
    )Please read the FAQ and learn how to post questions, so you can format your code, etc...
    http://wiki.oracle.com/page/Oracle+Discussion+Forums+FAQ

  • Self join sub query help

    This is my table
    Doctor     Appointment Date     Rating
    111     23/12/2009     G1
    111     23/12/2009     G2
    111     23/12/2009     B
    111          23/12/2009 D
    111     23/12/2008     G1
    111          23/12/2008 B
    111     23/12/2007     G2
    111          23/12/2007 B
    111     23/12/2006     D
    For Doctor 111, on a given appointment date he has multiple ratings.
    I have to fetch the rows (with doctor id, appointment date)
    I) which does not have G1 rating but has G2 rating for each appointment date
    And vice versa ( does not have G2 rating but has G1 rating for each appointment date)
    And
    II) if the particular appointment date has both G1 and G2 rating then I can ignore that appointment date – i.e do not fetch any rows if that appointment date has both G1 and G2 ratings.
    And
    III)     if the appointment date has no G1 or G2 rating, then display the appointment date and the doctor.
    So, my result set should have the output from all the three conditions for each doctor.
    I am not sure how it works. I am trying using correlated subqueries any suggestions???

    ME_XE?with data as
      2  (
      3     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'G1'   as app_type from dual union all
      4     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'G2'   as app_type from dual union all
      5     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'B'    as app_type from dual union all
      6     select 111 as doc_id, to_date('23/12/2009', 'dd/mm/yyyy') as app_date, 'D'    as app_type from dual union all
      7     select 111 as doc_id, to_date('23/12/2008', 'dd/mm/yyyy') as app_date, 'G1'   as app_type from dual union all
      8     select 111 as doc_id, to_date('23/12/2008', 'dd/mm/yyyy') as app_date, 'B'    as app_type from dual union all
      9     select 111 as doc_id, to_date('23/12/2007', 'dd/mm/yyyy') as app_date, 'G2'   as app_type from dual union all
    10     select 111 as doc_id, to_date('23/12/2007', 'dd/mm/yyyy') as app_date, 'B'    as app_type from dual union all
    11     select 111 as doc_id, to_date('23/12/2006', 'dd/mm/yyyy') as app_date, 'D'    as app_type from dual
    12  )
    13  select
    14     doc_id,
    15     app_date,
    16     app_type
    17  from
    18  (
    19     select
    20        sum( case when app_type = 'G1' then 1 else 0 end ) over (partition by doc_id, app_date) as g1,
    21        sum( case when app_type = 'G2' then 1 else 0 end ) over (partition by doc_id, app_date) as g2,
    22        doc_id,
    23        app_date,
    24        app_type
    25     from data
    26  )
    27  where g1 = 0 and g2 = 0
    28  or
    29  (
    30     g1 > 0 and g2 = 0
    31  )
    32  or
    33  (
    34     g2 > 0 and g1 = 0
    35  );
                DOC_ID APP_DATE                   APP_TY
                   111 23-DEC-2006 12 00:00       D
                   111 23-DEC-2007 12 00:00       B
                   111 23-DEC-2007 12 00:00       G2
                   111 23-DEC-2008 12 00:00       G1
                   111 23-DEC-2008 12 00:00       B
    5 rows selected.
    Elapsed: 00:00:00.59
    ME_XE?
    ME_XE?select * from v$version;
    BANNER
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    5 rows selected.
    Elapsed: 00:00:00.64Is one method using analytics (which allow you to perform operations over a 'window' of data, which seems to be what you need to do).

  • SQL server Query help

    I have four table like below:
    CREATE TABLE Party ( PartyID int identity(1,1)not null, PartyRegisteredDate datetime, MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2) )
    CREATE TABLE Contract ( ContractID int identity(1,1)not null, PartyID int, MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2) , ContractStartDate datetime, ContractEndDate datetime)
    CREATE TABLE IndividualContract ( IndContractID int identity(1,1)not null, ContractID int, PartyID int, MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2) ,ContractStartDate datetime, ContractEndDate datetime )
    CREATE TABLE Customer ( CustomerID int, IndContractID int, ContractID int, MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2))
    The business Key is MemberNo, SubsNo, PerNo in all the 4 tables.
    Contract table has PartyID as foreignKey from Party table
    IndividualContract table has ContractID,PartyID as foreignKeys from Party table and Contract table.
    Customer table has IndContractID,ContractID as foreignKeys from IndividualContract table.
    CustomerID in Customer table is nothing but PartyID.
    IndividualContract and Customer tables should be one-one.
    --Below is the source data in #Source table
    Create Table #Source (MemberNo varchar(16), SubsNo varchar(9), PerNo varchar(2),PartyRegisteredDate datetime, ContractStartDate datetime, ContractEndDate datetime)
    Insert into #Source
    Select '054911', '079548709', '01', '2002-09-01 00:00:00.000', '2012-08-01 00:00:00.000', '9999-12-31 00:00:00.000' union all
    Select '824212', '091547708', '01', '1987-07-14 00:00:00.000', '1987-07-14 00:00:00.000', '2010-09-01 00:00:00.000' union all
    Select '864211', '041609336', '01', '1993-01-01 00:00:00.000', '1999-03-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
    Select '864212', '113523275', '01', '1993-01-01 00:00:00.000', '1998-06-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
    Select '824212', '079548709', '02', '1987-07-14 00:00:00.000', '2010-09-01 00:00:00.000', '2010-09-01 00:00:00.000' union all
    Select '864211', '113523275', '02', '1993-01-01 00:00:00.000', '1999-03-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
    Select '864212', '041609336', '02', '1993-01-01 00:00:00.000', '1998-05-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
    Select '864212', '091547708', '03', '1993-01-01 00:00:00.000', '1998-06-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
    Select '867616', '041609336', '03', '1993-04-05 00:00:00.000', '1998-05-01 00:00:00.000', '1999-12-31 00:00:00.000' union all
    Select '867616', '113523275', '03', '1993-04-05 00:00:00.000', '1998-06-01 00:00:00.000', '1999-12-31 00:00:00.000'
    This source data should go to the above 4 tables.
    But the requirement is:
    1. For one MemberNo there should be only one row in Party table. So in my case ,the party table should have only 5 rows like below.
    PartyID PartyRegisteredDate MemberNo SubsNo PerNo
    1 1987-07-14 00:00:00.000 824212 091547708 01
    2 1993-01-01 00:00:00.000 864211 041609336 01
    3 1993-01-01 00:00:00.000 864212 113523275 01
    4 1993-04-05 00:00:00.000 867616 041609336 03
    5 2002-09-01 00:00:00.000 054911 079548709 01
    2. The contract table should have only records with PerNo='01' for one MemberNo.So in my case this table should have like below.
    ContractID PartyID MemberNo SubsNo PerNo ContractStartDate ContractEndDate
    1 1 824212 091547708 01 1987-07-14 00:00:00.000 2010-09-01 00:00:00.000
    2 2 864211 041609336 01 1993-01-01 00:00:00.000 1999-12-31 00:00:00.000
    3 3 864212 113523275 01 1993-01-01 00:00:00.000 1999-12-31 00:00:00.000
    4 5 054911 079548709 01 2002-09-01 00:00:00.000 9999-12-31 00:00:00.000
    3. The IndividualContract and Customer should have all the records from #Source table, as IndividualContract and Customer tables are one-one.
    4. IndivuidialContract table should look like below:
    Here the ContractID is based on the SubsNo from Contract table.
    IndContractID ContractID PartyID MemberNo SubsNo PerNo ContractStartDate ContractEndDate
    1 1 1 824212 091547708 01 1987-07-14 00:00:00.000 1988-09-30 00:00:00.000
    2 4 1 824212 079548709 02 2010-09-01 00:00:00.000 2010-09-01 00:00:00.000
    3 2 2 864211 041609336 01 1999-03-01 00:00:00.000 1999-03-01 00:00:00.000
    4 3 2 864211 113523275 02 1999-03-01 00:00:00.000 1999-12-31 00:00:00.000
    5 3 3 864212 113523275 01 1998-06-01 00:00:00.000 1999-12-31 00:00:00.000
    6 2 3 864212 041609336 02 1998-05-01 00:00:00.000 1998-05-31 00:00:00.000
    7 1 3 864212 091547708 03 1998-06-01 00:00:00.000 1998-06-01 00:00:00.000
    8 2 4 867616 041609336 03 1998-05-01 00:00:00.000 1998-05-01 00:00:00.000
    9 3 4 867616 113523275 03 1998-06-01 00:00:00.000 1999-12-31 00:00:00.000
    10 4 5 054911 079548709 01 2012-08-01 00:00:00.000 9999-12-31 00:00:00.000
    5. Customer table should look like below:
    IndContractId and ContractID for this table comes from IndivuidialContract table.
    CustomerID IndContractID ContractID MemberNo SubsNo PerNo
    1 1 1 824212 091547708 01
    1 2 4 824212 079548709 02
    2 3 2 864211 041609336 01
    2 4 3 864211 113523275 02
    3 5 3 864212 113523275 01
    3 6 2 864212 041609336 02
    3 7 1 864212 091547708 03
    4 8 2 867616 041609336 03
    4 9 3 867616 113523275 03
    5 10 4 054911 079548709 01

    Your DDL is wrong. No keys, NO way to have keys, singular table names (I am sorry you have only one customer), etc. You do not know the syntax for insertion, etc. You have no idea how to do a data model. Why is a party use a physical table property as an
    identifier?? Did you know about the DATE data type? 
    Why did you use IDENTITY? Why is the count of physical insertions an attribute of a contract in your mind? This is as silly as identifying a car by the parking space number in one garage! But not the VIN. 
    CREATE TABLE Parties
    (party_duns CHAR(9) NOT NULL PRIMARY KEY, 
     party_registration_date DATE DEFAULT CURRENT TIMESTAMP NOT NULL, 
     member_nbr CHAR(16) NOT NULL, 
     subs_nbr CHAR(9) NOT NULL, 
     per_nbr CHAR(2) NOT NULL NOT NULL);
    Do you know what a DUNS is and why it is a valid identifier for a party in a contract?  
    CREATE TABLE Contracts
    (contract_id CHAR(25) NOT NULL PRIMARY KEY, 
     party_duns CHAR(9) NOT NULL
      REFERENCES  Parties (party_duns), 
     member_nbr CHAR(16) NOT NULL, 
     subs_nbr CHAR(9) NOT NULL, 
     per_nbr CHAR(2) NOT NULL, 
     contract_start_date DATE DEFAULT CURRENT TIMESTAMP NOT NULL, 
     contract_end_date DATE, 
     CHECK (contract_start_date < contract_end_date));
    Why did you put the DRI in a useless narrative?? I guessed at one. 
    CREATE TABLE Individual_Contracts
    (ind_contract_id CHAR(25) NOT NULL,
     contract_id CHAR(25) NOT NULL, 
     party_duns CHAR(9) NOT NULL, 
     member_nbr CHAR(16) NOT NULL,
     subs_nbr CHAR(9) NOT NULL,
     per_nbr CHAR(2) NOT NULL, 
     contract_start_date DATE DEFAULT CURRENT TIMESTAMP NOT NULL,
     contract_end_date DATE)
    CREATE TABLE Customers
    ( CustomerID  int, 
     indcontract_id int,
     contract_id  CHAR(25) NOT NULL,
     member_nbr CHAR(16) NOT NULL,
     subs_nbr CHAR(9) NOT NULL,
     per_nbr CHAR(2) NOT NULL)
    >> The business Key is member_nbr, subs_nbr, per_nbr in all the 4 tables. <<
    That is a design flaw. A key should locate one and only one entity in the schema. But you have split the entity over many tables. 
    >> Contract table has party_id as foreign Key from Parties table <<
    Where is the DDL for this??? 
    >> IndividualContract table has contract_id, party_id as foreignKeys from Parties table and Contract table. <<
    Where is the DDL for this??? 
    >> Customer table has Indcontract_id, contract_id as foreignKeys from IndividualContract table. <<
    Where is the DDL for this??? 
    >> CustomerID in Customer table is nothing but party_id. <<
    Redundancy is the reason we moved from files to DBs. 
    >> IndividualContract and Customer tables should be one-one. <<
    Where is the DDL for this??? 
    You almost know what you are doing , which is a nice change from most postings here. But I cannot donate $$$$ hours of consulting to you. For example, why is an individual contract totally different form a mere contract? Etc. 
    --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

  • Sub Query Help

    First, I'm new to oracle so please bear with me....
    I have the current query which works great:
    SELECT
    CASE WHEN (RX.STORENBR = '101114') THEN 'CC-FTL'
    WHEN (RX.STORENBR = '103073') THEN 'CC-MIA'
    WHEN (RX.STORENBR = '102520') THEN 'CC-WPB'
    ELSE '0'
    END AS PHARMACY_NAME,
    CASE WHEN (RX.STORENBR = '101114') THEN '1598762015'
    WHEN (RX.STORENBR = '103073') THEN '1063423606'
    WHEN (RX.STORENBR = '102520') THEN '1770580292'
    ELSE '0'
    END AS PHARMACY_NPI,
    CASE WHEN (RX.STORENBR = '101114') THEN '1079638'
    WHEN (RX.STORENBR = '103073') THEN '1019303'
    WHEN (RX.STORENBR = '102520') THEN '1099286'
    ELSE '0'
    END AS PHARMACY_NCPDP,
    CASE WHEN (RX.STORENBR = '101114') THEN 'BN9568861'
    WHEN (RX.STORENBR = '103073') THEN 'BN9754450'
    WHEN (RX.STORENBR = '102520') THEN 'BA8399962'
    ELSE '0'
    END AS PHARMACY_DEA,
    PATIENT.PATSTOREID AS PT_STORE,
    PATIENT.PATKEY AS PT_KEY,
    (PATIENT.PATSTOREID || LPAD(PATIENT.PATKEY, 6, 0)) AS PTID,
    DOCTOR.NAMELAST AS PRESCRIBER_LAST,
    DOCTOR.NAMEFIRST AS PRESCRIBER_FIRST,
    DOCTOR.ADRSCITY AS PRESCRIBER_CITY,
    DOCTOR.ADRSSTATE AS PRESCRIBER_STATE,
    DOCTOR.ADRSZIP AS PRESCRIBER_ZIP,
    DOCTOR.STATENUMBER,
    DOCTOR.DEAALPHAALPHA || DOCTOR.DEAALPHANBR || DOCTOR.DEAALPHASFX AS PRESCRIBER_DEA,
    CASE WHEN (DOCTOR.PLANCODE01 = 'NPI') THEN DOCTOR.PLANID01
    WHEN (DOCTOR.PLANCODE02 = 'NPI') THEN DOCTOR.PLANID02
    WHEN (DOCTOR.PLANCODE03 = 'NPI') THEN DOCTOR.PLANID03
    ELSE '0'
    END AS NPI,
    DOCTOR.SPECIALTY,
    DRUG.NAME, DRUG.DRUGNDCNBR,
    PLANS.PLANID,
    (NVL(RX.CASHPAID, 0)/100) AS COPAY,
    to_char(to_date(RX.FILLDATE, 'yyyyddd'), 'MM/DD/YYYY') AS DISPENSED_DATE,
    RX.DISPENSEDQTY01, RX.DAYSUPP,
    FROM RX
    LEFT OUTER JOIN PLANS ON (RX.PLANSTOREID01=PLANS.PLANCODESTOREID AND RX.PLANKEY01=PLANS.PLANCODEKEY)
    LEFT OUTER JOIN DRUG ON (RX.DISPENSEDDRUGSTOREID=DRUG.DRUGNBRSTOREID AND RX.DISPENSEDDRUGKEY=DRUG.DRUGNBRKEY)
    LEFT OUTER JOIN DOCTOR ON (RX.DOCNBRSTOREID=DOCTOR.DOCSTOREID AND RX.DOCNBRKEY = DOCTOR.DOCKEY)
    LEFT OUTER JOIN PATIENT ON (RX.PATNBRSTOREID=PATIENT.PATSTOREID AND RX.PATNBRKEY=PATIENT.PATKEY)
    WHERE RX.FILLDATE >= 2007274
    AND RX.FILLDATE <= 2007304
    AND DRUG.DRUGNDCNBR = 0004038039
    AND NVL(RX.RXSTATUS, 0) <> 16
    AND NVL(RX.RXSTATUS, 0) <> 17
    AND NVL(RX.RXSTATUS, 0) <> 18
    AND NVL(RX.RXSTATUS, 0) <> 20
    AND NVL(RX.RXSTATUS, 0) <> 24
    AND NVL(RX.RXSTATUS, 0) <> 32
    AND NVL(RX.RXSTATUS, 0) <> 33
    AND NVL(RX.RXSTATUS, 0) <> 48
    However, I also want to add a subquery to return the LEAST(RX.FILLDATE) on each Patient.Patkey. I belive the subquery should be something like this:
    SELECT * FROM (
    SELECT RX.FILLDATE AS FIRST_DATE
    FROM RX
    LEFT OUTER JOIN DRUG ON (RX.DISPENSEDDRUGSTOREID=DRUG.DRUGNBRSTOREID AND RX.DISPENSEDDRUGKEY=DRUG.DRUGNBRKEY)
    WHERE RX.PATNBRSTOREID=PT_STORE
    AND RX.PATNBRKEY=PT_KEY
    AND DRUG.DRUGNDCNBR = 0004038039
    ORDER BY LEAST(RX.FILLDATE)
    WHERE ROWNUM = 1
    How do I format the subquery so oracle performs the lookup on each record returned in the main query, based on the main query's "WHERE" Clause?

    Don't know if your version supports subquery factoring this way the whole thing is much more evident
    with
    the_query as
    < your query here >
    the_subquery as
    < your subquery here >
    select the_query.*,the_subquery.*
      from the_query
      left outer join the_subquery on (< join conditions here >)or (in old notation)
    select q.*,s.*
      from (< your query here >) q,
           (< your subquery here >) s,
    where < join conditions here > Regards
    Etbin

  • Sql Update Query help!!!..

    Hi Guys,
    below is the table , i am trying to update error_flg of records which have ID=2, NAME ='janice' to 2 if the error_flg is '0' and to '3' if the error flag is '1',
    the bold are the records i want to update and i am also showing the result below in highlighted
    CREATE TABLE person
    ID NUMBER(12),
    person_ID NUMBER(16),
    NaME VARCHAR2(15 BYTE),
    USERID VARCHAR2(7 BYTE),
    error_flg VARCHAR2(1 BYTE)
    insert into person (id,person_id,name,userid,error_flg) values(1,100,'micheal','userid','1')
    insert into person (id,person_id,name,userid,error_flg) values(1,101,'steve','userid','1')
    insert into person(id,person_id,name,userid,error_flg) values(1,102,'janice','userid','1')
    insert into person (id,person_id,name,userid,error_flg) values(2,103,'janice','userid','1')
    insert into person (id,person_id,name,userid,error_flg) values(2,104,'janice','userid','0')
    insert into person (id,person_id,name,userid,error_flg) values(3,105,'janice','userid','0')
    result should be:
    insert into person (id,person_id,name,userid,error_flg) values(1,100,'micheal','userid','1')
    insert into person (id,person_id,name,userid,error_flg) values(1,101,'steve','userid','1')
    insert into person(id,person_id,name,userid,error_flg) values(1,102,'janice','userid','1')
    insert into person (id,person_id,name,userid,error_flg) values(2,103,'janice','userid','3')
    insert into person (id,person_id,name,userid,error_flg) values(2,104,'janice','userid','2')
    insert into person (id,person_id,name,userid,error_flg) values(3,105,'janice','userid','0')
    Edited by: oraclebeginner1231 on Jun 10, 2010 8:52 AM

    oraclebeginner1231 wrote:
    that was smart..why did i not think .. also how to combine both?
    thanks a lotYou can use a CASE statement to achieve that.
    update person
       set error_flg = case when error_flg = '0' then '2' when error_flg = '1' then '3' end
    where id    = 2
    and   name  = 'janice'
    and   error_flg in ('0', '1');

  • SQL Query Help - Is this possible or impossible????

    Hi guys,
    I need help with an SQL query that I'm trying to develop. It's very easy to explain but when trying to implement it, I'm struggling to achieve the results that I want.....
    For example,
    I have 2 tables
    The first table is:
    1) COMPANY create table company (manufacturer varchar2(25),
                                                          date_established date,
                                                          location varchar2(25) );My sample test date is:
    insert into company values ('Ford', 1902, 'USA');
    insert into company values ('BMW', 1910, 'Germany');
    insert into company values ('Tata', 1922, 'India');The second table is:
    2) MODELS create table models (manufacturer varchar(25),
                                                 model varchar2(25),
                                                 price number(10),
                                                 year date,
                                                 current_production_status varchar2(1) ) ;My sample test data is:
    insert into models values ('Ford', 'Mondeo', 10000, 2010, 0);
    insert into models values ('Ford', 'Galaxy', 12000,   2008, 0);
    insert into models values ('Ford', 'Escort', 10000, 1992, 1);
    insert into models values ('BMW', '318', 17500, 2010, 0);
    insert into models values ('BMW', '535d', 32000,   2006, 0);
    insert into models values ('BMW', 'Z4', 10000, 1992, 0);
    insert into models values ('Tata', 'Safari', 4000, 1999, 0);
    insert into models values ('Tata', 'Sumo', 5500,   1996, 1);
    insert into models values ('Tata', 'Maruti', 3500, 1998, 0);And this is my query:
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer IN ('Ford', 'BMW', 'Tata')
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCWhat I want the query to output is this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               Sumo               5500               1998          1If current_production_status is 1 it means this particular model has been discontinued
    If current_production_status is 0 it means the manufacturer does not have any discontinued models and all are in procuction.
    The rule is only one record per manufacturer is allowed to have a current_production_status of 1 (so only one model from the selection the manufactuer offers is allowed to be discontinued).
    So the query should output the one row where current_production_status is 1 for each manufacturer.
    If for a given manufacturer there are no discontinued models and all have a current_production_status of 0 then ouput a SINGLE row that only includes the data from the COMPANY table (as above). The rest of the columns from the MODELS table should be populated with a '-' (hyphen).
    My query as it is above will output all the records where current status is 1 or 0 like this
    com.manufacturer        com.date_established          com.location          mod.model          mod.price          mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    Tata               1922                    India               Sumo               5500               1998          1
    Ford               1902                    USA               -               -               -          0                    
    Ford               1902                    USA               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               -               -               -          0
    Tata               1922                    India               -               -               -          0However this is not what I want.
    Any ideas how I can achieve the result I need?
    Thanks!
    P.S. Database version is '10.2.0.1.0'

    Hi Vishnu,
    Karthiks query helped...
    But this is the problem I am facing...
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer = 'Ford'
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCThe value of:
    and com.manufacturer = 'Ford'will be dependent on front end user input....
    When I run the query above I get all the rows where current_production_status is either 1 or 0.
    I only require the rows where current_production_status is 1.
    So if I amend it to look like this:
         and mod.current_production_status = 1This works....
    BUT if a user now passes in more than one manufacturer EG:
    and com.manufacturer IN ('Ford', 'BMW')The query will only return the one row for Ford where current_production_status is 1. However because BMW has no models where current_production_status is 1 (all 3 are 0), I still want this to be output - as one row....
    So like this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0So (hopefully you understand), I want both cases to be catered for.....whether a user enters one manufacturer or more than one...
    Thanks you so much!
    This is really driving me insane :-(

Maybe you are looking for

  • Safari, iChat & SoftwareUpdater suddenly not working.

    Recently certain applications on my computer haven't been working. Whenever I open any of the following applications (Safari, iChat & Software Updater),I get the rolling little beachball and it freezes up the program. What is causing this and what ca

  • Dynamic hyperlink from database table

    hi, I have requirement to create left hand menu on a page. Menu label and hyperlink is stored in database. What is the best way to achieve this. Basically when user logs based on his user name query will fetch the labels and hyperlink source. How to

  • Optional parameters

    Can the procedures or the packages have optional parameters?

  • No sound on my hp pavilion dv8000

      After upgrading to  windows 7 ultimate on my hp pavilion dv 8000 s#[edited by Moderator]us p/h EP407UA#ABA  I   am unable to complete the  download  of  the  sound driver  and I get the  (code 10)

  • RubyOnRails hosted with Oracle Appliation Server (very slow)

    Hi, i tried to host a rubyOnRails application on a oracle application server (more precisley: the included Apache). The test to use fastcgi stops with segmentation fault in the ruby framework.... I am using Solaris 10 and installed ruby via www.sunfr