SQL column as select statement to be referenced into a group by

Is there a notation or solution to be able to reference a column that is a inline select statement within a group by as detailed below? The group by will not accept the alias. I also tried to make the SQL a MAX to remove the need for the group by reference and this returned invalid expression.
SELECT DISTINCT hdr.BUSINESS_UNIT,
hdr.SESSN_ID,
hdr.STREAM_ROOT_ID,
hdr.SESSN_STS_CD,
hdr.SESSN_CRE_DTTM,
CASE
WHEN C.OPRID <> ' ' THEN C.OPRID
ELSE S.OPERATOR
END OPRID,
strm.QS_APP_CONTEXT,
RECV.QTY_SH_RECVD Quantity_Received,
CASE
WHEN hdr.BUSINESS_UNIT = 'MFG01' THEN MAX(G.MFDS_SGRP_SIZE)
ELSE MAX(S.SESSN_SGRP_SIZE)
END Quantity_Inspected,
MAX(S.QS_VALUEREADING_1) Defect_Count,
CASE
WHEN MAX(S.QS_VALUEREADING_1) = 0 THEN ' '
ELSE MAX(G.MFDS_NAME)
END Characteristic,
MAX(CMNT.QS_COMMENT2) COMMENTS,
strm.INV_ITEM_ID,
itm.DESCR,
strm.WORK_CENTER_CODE,
strm.VENDOR_ID,
*(SELECT V.NAME1 FROM PS_VENDOR V WHERE strm.VENDOR_ID = V.VENDOR_ID AND V.SETID = (SELECT SETID FROM PS_SET_CNTRL_REC*
WHERE  RECNAME = 'VENDOR'
AND SETCNTRLVALUE = strm.BUSINESS_UNIT)) VENDOR_NAME,
strm.PRDN_AREA_CODE,
strm.COMPL_OP_SEQ,
strm.PRODUCTION_TYPE,
C.RECEIVER_ID,
C.RECV_LN_NBR,
RECV.PO_ID,
RECV.LINE_NBR,
RECV.SCHED_NBR,
C.PRODUCTION_ID,
C.SERIAL_ID,
C.INV_LOT_ID
FROM PS_QS_SESSN_HDR8 hdr
LEFT OUTER JOIN PS_QS_SESSN_TRACE8 C
ON hdr.BUSINESS_UNIT = C.BUSINESS_UNIT
AND hdr.SESSN_ID = C.SESSN_ID
LEFT OUTER JOIN PS_RECV_INSPDTL_VW RECV
ON C.BUSINESS_UNIT = RECV.BUSINESS_UNIT
AND C.RECEIVER_ID = RECV.RECEIVER_ID
AND C.RECV_LN_NBR = RECV.RECV_LN_NBR
LEFT OUTER JOIN PS_QS_STREAM_ROOT strm
ON hdr.STREAM_ROOT_ID = strm.STREAM_ROOT_ID
AND hdr.BUSINESS_UNIT = strm.BUSINESS_UNIT
LEFT OUTER JOIN PS_QS_STREAM8_VW G
ON strm.STREAM_ROOT_ID = G.STREAM_ROOT_ID
AND strm.BUSINESS_UNIT = G.BUSINESS_UNIT
LEFT OUTER JOIN PS_QS_SUBGROUP S
ON hdr.BUSINESS_UNIT = S.BUSINESS_UNIT
AND hdr.SESSN_ID = S.SESSN_ID
AND S.STREAM_ID = G.STREAM_ID
LEFT OUTER JOIN PS_QS_SESSN_COMM8 CMNT
ON S.BUSINESS_UNIT = CMNT.BUSINESS_UNIT
AND S.SESSN_ID = CMNT.SESSN_ID
AND S.STREAM_ID = CMNT.STREAM_ID
AND C.SAMPLE = CMNT.SAMPLE
LEFT OUTER JOIN PS_MASTER_ITEM_TBL itm
ON itm.INV_ITEM_ID = strm.INV_ITEM_ID
LEFT OUTER JOIN PS_SET_CNTRL_REC cntrl
ON itm.SETID = cntrl.SETID
AND cntrl.RECNAME = 'MASTER_ITEM_TBL'
AND cntrl.SETCNTRLVALUE = strm.BUSINESS_UNIT
WHERE S.QS_VALUEREADING_1 = (SELECT MAX(S2.QS_VALUEREADING_1)
FROM PS_QS_SUBGROUP S2
WHERE S2.BUSINESS_UNIT = S.BUSINESS_UNIT
AND S2.SESSN_ID = S.SESSN_ID
AND S2.STREAM_ID = S.STREAM_ID)
GROUP BY hdr.BUSINESS_UNIT,
hdr.SESSN_ID,
hdr.STREAM_ROOT_ID,
hdr.SESSN_STS_CD,
hdr.SESSN_CRE_DTTM,
C.OPRID,
S.OPERATOR,
strm.QS_APP_CONTEXT,
RECV.QTY_SH_RECVD,
strm.INV_ITEM_ID,
itm.DESCR,
strm.WORK_CENTER_CODE,
strm.VENDOR_ID,
VENDOR_NAME,
strm.PRDN_AREA_CODE,
strm.COMPL_OP_SEQ,
strm.PRODUCTION_TYPE,
C.RECEIVER_ID,
C.RECV_LN_NBR,
RECV.PO_ID,
RECV.LINE_NBR,
RECV.SCHED_NBR,
C.PRODUCTION_ID,
C.SERIAL_ID,
C.INV_LOT_ID

Hi,
Assign the alias in a sub-query. Then you'll be able to use it wherever you want to, and how many times you want to, in a super-query.
For example:
WITH     got_vendor     AS
     SELECT     hdr.business_unit
              SELECT  v.name1
              FROM    ps_vendor     v
              WHERE   strm.vendor_id     = v.vendor_id
              AND     v.setid          = (
                                            SELECT  setid
                                    FROM    ps_set_cntrl_rec
                                    WHERE   recname          = 'VENDOR'
                                    AND     setcntrlvalue      = strm.business_unit
          )           AS vendor_name
     FROM      ps_qs_sessn_hdr8     hdr
SELECT       business_unit          -- NOTE: no hdr.; all columns are from got_vendor now
,       vendor
FROM       got_vendor
GROUP BY  business_unit
,       vendor
;When you define an alias (such as vendor) in a query, you can use that alias in the ORDER BY clause of that same query, but that's the only place in that same query where you can use it. If you want to use the alias anywhere else (e.g., in the GROUP BY clause, as in your example, the WHERE clause, or elsewhere in the SELECT clause), then you probably want to compute it in a sub-query, as shown above.
There's probably a better way to compute vendor, but that's a separate problem.
Edited by: Frank Kulash on Jan 3, 2012 10:37 AM
Added example

Similar Messages

  • Select statement inside function with  into keyword

    Hi Everyone,
    i have a function which contains a select statement
    create or replace
    function fun_1(Table_Name1 in varchar2)
    RETURN VARCHAR2
    is
    VAR_GEN_TYPE NUMBER(10);
    TA_U varchar2(256);
    VAR_DATA_FLAG varchar2(1);
    begin
    select T.FLAG into VAR_GEN_TYPE ,T.DATA_UID_GEN_TYPE into VAR_DATA_FLAG  from T_DYNAMIC_TABLE T  where T.TABLE_NAME=TABLE_NAME1;
    end
    whene ever i am executing this function giving error message: From Keyword  Not Found
    when i change select statement to
    select T.FLAG ,T.DATA_UID_GEN_TYPE into VAR_DATA_FLAG, VAR_GEN_TYPE from T_DYNAMIC_TABLE T where T.TABLE_NAME=TABLE_NAME1;
    then it is working
    why first statements will not work ?
    i.e.,
    select T.FLAG into VAR_GEN_TYPE ,T.DATA_UID_GEN_TYPE into VAR_DATA_FLAG from T_DYNAMIC_TABLE T where T.TABLE_NAME=TABLE_NAME1;
    why in select statement we cannot use into keyword more than one time ?
    Edited by: karteek on Jun 7, 2012 4:23 AM
    Edited by: karteek on Jun 7, 2012 4:24 AM

    select T.FLAG into VAR_GEN_TYPE ,T.DATA_UID_GEN_TYPE into VAR_DATA_FLAG, from T_DYNAMIC_TABLE T where T.TABLE_NAME=TABLE_NAME1;
    into should be only once..
    the syntax should be
    select <column list>
    into
    <variable list>
    from <table name> where <condition>
    --This query shuold return only one row.
    column list count and variable list count should match
    there should be no comma after last variable.andbefore from.

  • Benefit of using store procedure instead of select statement to pull data into biztalk

    I was wondering why store procedure is more beneficial than using select statement to pull data into biztalk?

    In addition to the above two points, in case if there is a change in logic of stored procedure, you only need to modify the stored proc and the applications calling/using it may be left intact.
    Also, stored procedures are complied code so performance is better and safe too.
    Thanks,
    Prashant
    Please mark this post accordingly if it answers your query or is helpful.

  • Retrieving multiple values from one column in SELECT statement

    Hi,
    I have a slight dilemma in that I'm trying to pull down all the values from a column from a select statement that includes some JOINS in it.
    If I run the query at the SQL Plus prompt, it pulls back all the values/rows.
    When I run the select (and prepared ) statement in my JSP, it only pulls back one of the 4 values I'm trying to retrieve.
    e.g.
    at the DB level :
    SELECT role_name, CC_ID FROM votetbl a
    INNER JOIN APPROVERS b ON
    a.BUSVP = b.BUSVP AND
    a.BRANCH = b.BRANCH
    WHERE CC_ID = 1688this will return:
    ROLE_NAME CC_ID
    ops 1688
    ops 1688
    comply 1688
    legal 1688
    comply 1688
    When run in my JSP, like so:
    String primID3a = request.getParameter("primID");
    Statement stmtovoter = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    String prepvotSQL = "SELECT role_name, CC_ID FROM votetbl a INNER JOIN APPROVERS b ON a.BUSVP = b.BUSVP AND " +
                         "a.BRANCH = b.BRANCH WHERE CC_ID = ?";
    PreparedStatement prepvotstmt = connection.prepareStatement(prepvotSQL);
    prepvotstmt.setString(1, primID3a);
    ResultSet rest3 = prepvotstmt.executeQuery();
    rest3.next();
    String votecat = rest3.getString(1);
    out.println("Vote category: "+votecat);I only get ops returned.
    Do I need to run an enumerator? Or reqest.getParameterValues or use a while statement around the results set?
    Any feedback and direction here is welcomed!
    Thanks!

    Actually, I tried looping and still only get 1, but returned several times.
    i.e.
    PreparedStatement prepvotstmt = connection.prepareStatement(prepvotSQL);
    prepvotstmt.setString(1, primID3a);
    ResultSet rest3 = prepvotstmt.executeQuery();
    rest3.next();
    String votecat = rest3.getString(1);
    while (rest3.next()) {
    out.print("category roles "+votecat);
    }then I get returned the following:
    admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admin
    like so.
    Where as at the DB level I get
    ROLE_NAME CC_ID
    admin 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    ops 1688
    risk 1688
    comply 1688
    legal 1688
    legal 1688
    ops 1688
    comply 1688
    Maybe the while should go around the getString(1) designation? But I was thinking I'd tried that and gotten invalid cursor error
    Something is definitely amiss, between the prepared statement in the servlet and the SELECT statement at the DB level.
    I can totally hardcode the statement in the servlet or JSP and it will return one value potentially several times, but only one.
    Other times, it will not return a value at all, even though one resides in the db.
    Yet go to the DB/SQL Plus prompt and it returns perfectly. I can simply copy and paste the SELECT statement from the out.print line I made and it works like a champ in SQL Plus. Any ideas why the same exact thing cannot return the proper values within the servlet/JSP?
    Yeeeeeeesh!!! : (
    Message was edited by:
    bpropes20

  • Adding columns in select statements

    All if i have the following statement and i wanted to add the two volume columns in the select statement can i just do a A1.volume + A2.Volume as vol
    SELECT A1.ORDERID,A1.MARKET,A1.GIMSG, A2.ORDERID,A2.MARKET,A2.TRADERID, A1.VOLUME, A2.VOLUME
    FROM table1 A1 JOIN table2
      ON A1.TRADEDATE = A2.TRADEDATE

    No that wouldnt work,
    Error will be invalid no(error no ORA-01722)
    but you can use pipe(||)
    select col1||col2 as col from ......
    ex: SQL> select e.ename||d.dname as result_col from emp e,dept d where e.deptno=d.deptno;
    RESULT_COL
    SMITHRESEARCH
    ALLENSALES
    WARDSALES
    JONESRESEARCH
    MARTINSALES
    BLAKESALES
    CLARKACCOUNTING
    SCOTTRESEARCH
    KINGACCOUNTING
    TURNERSALES
    ADAMSRESEARCH
    RESULT_COL
    JAMESSALES
    FORDRESEARCH
    MILLERACCOUNTING
    14 rows selected.
    Message was edited by:
    user517498

  • PL/SQL Function in Select statement

    Hi
    I am calling a function in select statement. The query works in Toad and PL/SQL developer except SQL plus and disconnecting Oracle connection.
    The error is “ERROR at line 1: ORA-03113: end-of-file on communication channel”.
    When I called the same query from BC4J View Object the error message is “java.sql.SQLException: No more data to read from socket”.
    Can any one advise me please?
    Thanks
    Srini

    Srini
    I've seen similar cases in the past with 9.2.0.x (x <= 5). What Oracle version are you using? It's worth checking the bug database (I can't just now - I don't have a valid support id in my current contract). And as Warren says, post your SQL query.
    HTH
    Regards nigel

  • How: making column value as column of select statement

    Hi
    Quickly I have searched in this forum for following solution but not able to find it.
    I need to make a query in such a way that the value of one column in one table should act as a column-name of another table
    Eg:-
    tab1
    col1,col2,*col3*,col4
    tab2
    col11 col22 col33 col44
    row1 a b col3 d
    row2 aa bb cc dd
    So the query should be something like --- in row2 if the value is col3 then from tab1 I should pick the col3 in select statement (basically there will be some join in tab1 and tab2 )
    Hope I am able to make u all understand my query.
    regards

    Hi all,
    Sorry for late response.Just now I checked all the replies.
    Actually I tried in this way.
    CREATE OR REPLACE function Proc_caption (in_tan varchar2, in_order in number)
    return varchar2
    is
    d varchar2(100) ;
    begin
    SELECT col1 into d
    from tab1
    Where
    col2 = in_tanid
    AND col3 = 'Y'
    AND col4 = in_order ;
    return d ;
    Exception
    WHen No_DATA_FOund then
    return 'N' ;
    end ;
    create or replace procedure proc_generate_view(in_tan varchar2, in_soc varchar2)
    is
    x varchar2(2000);
    v4 varchar2(50) ;
    v5 varchar2(50) ;
    cnt number ;
    begin
    v4:= PROC_Caption (in_tan,4) ;
    v5:= PROC_Caption (in_tan,5) ;
    x := ' Create view v_generate as '
    || ' SELECT a , b, c, d ' ;
    if v4 <> 'N' THEN
    x := x || ' , ' || PROC_Caption (in_tan,4) || ' as Caption4 ' ;
    end if;
    if v5 <> 'N' THEN
    x := x || ' , ' || PROC_Caption (in_tan,5) || ' as Caption5 ' ;
    end if;
    x := x || ' FROM tab2 WHERE col1 = ''' || in_socid || ''''
    || ' AND col2 = ''' || in_tan || '''' ;
    select count(1) into cnt from USER_OBJECTS where OBJECT_NAME = 'V_GENERATE'
    and OBJECT_TYPE = 'VIEW' ;
    if cnt > 0 then
    EXECUTE IMMEDIATE ' DROP view V_GENERATE' ;
    END IF ;
    execute immediate x ;
    end ;
    NOTE:- I have just renamed the table name and column names in order to make it non confedential...
    I have created this successfully with actual table name and column names and able to get the result as per my requirement.
    regards

  • Sql Error in Select statement when doing subquery

    Hi,
    I am trying to see what the error is in the subquery part of the select statement.
    Subquery should be fetching the safety_stock_quantity based on the MAX(effectivity_date).
    Any suggestions?
    SELECT kbn.last_update_date,itm.segment1,itm.description,kbn.kanban_card_number,kbn.kanban_size,
                   (SELECT msc.safety_stock_quantity
    FROM mtl_safety_stocks msc
    WHERE msc.effectivity_date = (select MAX(msc2.effectivity_date)
                   from mtl_safety_stocks msc2
                                            where msc2.inventory_item_id = itm.inventory_item_id
                                                 and msc2.organization_id = itm.organization_id)
                   AND msc.inventory_item_id = itm.inventory_item_id
         AND msc.organization_id = itm.organization_id                                        
    FROM mtl_system_items_b itm
    ,mtl_onhand_quantities_detail moqd
              ,mtl_safety_stocks msc
              ,mtl_kanban_card_activity kbn
    WHERE itm.inventory_item_id = kbn.inventory_item_id
    AND itm.organization_id = kbn.organization_id
    AND itm.inventory_item_id = moqd.inventory_item_id
    AND itm.organization_id = moqd.organization_id
    AND moqd.subinventory_code = kbn.source_subinventory
         AND kbn.card_status = 1
         AND kbn.supply_status = 5
         AND msc.inventory_item_id = itm.inventory_item_id
         AND msc.organization_id = itm.organization_id     
    GROUP BY
    kbn.last_update_date,itm.segment1,itm.description,kbn.kanban_card_number,kbn.kanban_size;
    Thanks
    Pravn

    Hi, Pravn,
    Remember the ABC's of GROUP BY:
    When you use a GROUP BY clause and/or an aggregate fucntion, then every item in the SELECT clause must be:
    (A) an <b>A</b>ggregate function,
    (B) one of the "group <b>B</b>y" expressions,
    (C) a <b>C</b>onstant, or
    (D) something that <b>D</b>epends entirely on the above. (For example, if you "GROUP BY TRUNC(dt)", you can "SELECT TO_CHAR (TRUNC(dt), 'Mon-DD')").
    There's a GROUP BY clause in your main query, so every item in the main SELECT clause must be one of the above. The last item, the unnamed scalar sub-query, is none of the above.
    How can you fix this problem? That depends on your data, the results you want, and perhaps on your Oracle version. If you'd like help, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved. Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Always say which version of Oracle you're using.
    You may have noticed that this site normally doesn't display multiple spaces in a row.
    Whenever you post formatted text (including, but limited to, actual code) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Columns in Select Statement

    Does the column selected in the select statement will effect the table access. I have a query selecting 10 columns from different tables using joins and inline views. One table is going for a Full table Scan.
    When I searched for the cause, I couldn't find anything. Everything looks correct. When I comment 2 two particular columns from the select statement the table is not scanned fully.
    Those two columns are not the part of the index. Why does a selection of columns affect the Explain plan?
    Thanks,
    GM

    Hi Gints,
    Thank you for your reply. This is my query and
    nvl(TICKET_JOIN.TDQRLV,0) ACC_SHIPPED_QTY,
    TICKET_JOIN.TDSOQS QUANTITY_TICKETED are the columns tha's creating issue. If I comment those columns Index is accessed properly.
    select
    'TKT' SOURCE,
    TICKET_JOIN.TKDO01 HIRE_ID,
    TICKET_JOIN.TKQ101 TRUCK_ID,
    TICKET_JOIN.TKVEHT TRUCK_TYPE,
    1 TRUCK_COMM,
    nvl(TKCMP1,0) TICKET_NUM,
    nvl(TKADTM,0) TICKET_TIME,
    --TICKET_JOIN.TDSOQS QUANTITY_TICKETED,
    0 CHECKIN_TIME,
    --nvl(TICKET_JOIN.TDQRLV,0) ACC_SHIPPED_QTY,
    nvl(DDADTM,0) START_TIME
    from
    (select
    TICKET.TKCMP1,
    TICKET.TKDO01,
    TICKET.TKQ101,
    TICKET.TKADTM ,
    TICKET.TKVEHT,
    TICKET_DETAILS.TDAITM ,
    TICKET_DETAILS.TDQRLV ,
    TICKET_DETAILS.TDSOQS ,
    TICKET.TKCNTF,
    TICKET.TKTRDJ,
    TICKET.TK58GA8
    from
    CRPDTA.F5800091 TICKET_DETAILS ,
    CRPDTA.F5800090 TICKET
    where TICKET.TKCMP1 = TICKET_DETAILS.TDCMP1
    and TICKET.TKTRDJ = TICKET_DETAILS.TDTRDJ
    and TICKET.TKTRDJ = 107085
    and TICKET.TKEV12 <> 'Y'
    and TICKET.TK58GA8='ECSEO'
    and TICKET.TKCNTF = '11') TICKET_JOIN ,
    (select
    DDDOCO,
    DDCNTF,
    DDQTFN,
    DDAITM,
    DDADTM,
    DD58GA8,
    DDTRDJ
    from
    CRPDTA.F5800051 ORDER_DETAILS,
    CRPDTA.F5800050 ORDER_HEADER
    where
    ORDER_HEADER.DHDOCO = ORDER_DETAILS.DDDOCO
    and ORDER_HEADER.DHTRDJ = ORDER_DETAILS.DDTRDJ
    and ORDER_HEADER.DH58GA8 = ORDER_DETAILS.DD58GA8
    and ORDER_HEADER.DHDCTO = ORDER_DETAILS.DDDCTO
    /*and
    (ORDER_HEADER.DHTRDJ = 107085
    OR (ORDER_HEADER.DHTRDJ = 107084 and ORDER_HEADER.DHEV04='Y')
    and TRIM(ORDER_HEADER.DH58GA8) = 'ECSEO'
    and TRIM(ORDER_DETAILS.DDCNTF) = '11' ) ORDER_VIEW
    where TICKET_JOIN.TKTRDJ = ORDER_VIEW.DDTRDJ
    and TICKET_JOIN.TDAITM = ORDER_VIEW.DDAITM
    and TICKET_JOIN.TKCNTF = ORDER_VIEW.DDCNTF
    and TICKET_JOIN.TK58GA8 = ORDER_VIEW.DD58GA8
    and NOT EXISTS ( select 1 from CRPDTA.F5800120 TRUCK_ASSIGNMENT
    where TATRDJ = 107085
    and TACNTF = '11'
    and TA58GA8 = 'ECSEO'
    and TICKET_JOIN.TKQ101||TICKET_JOIN.TKVEHT = TAQ101||TAVEHT )
    Thanks
    GM

  • Calling PL/SQL code from Select statement

    Hi
    I have a PL/SQL function to calculate a value.
    create or replace procedure "SR_GROSS_MARGIN"
    (netsales IN NUMBER,
    margin IN NUMBER,
    GM OUT NUMBER)
    is
    BEGIN
        IF NETSALES = 0 THEN
           GM := 0;
        ELSIF
           NETSALES < 0 THEN
           GM := 0;
        ELSE
           GM := NETSALES / MARGIN;
        END IF;
    END;How do I call this from a SELECT statement?
    Regards
    Adam

    here you go:
    create or replace function SR_GROSS_MARGIN
    (netsales IN NUMBER,
    margin IN NUMBER)
    return number
    is
    gm number;
    BEGIN
        IF NETSALES = 0 THEN
           GM := 0;
        ELSIF
           NETSALES < 0 THEN
           GM := 0;
        ELSE
           GM := NETSALES / MARGIN;
        END IF;
    return gm;
    END;then you can:
    select gm(2500,20) from dual;

  • SQL insert with select statement having strange results

    So I have the below sql (edited a bit). Now here's the problem.
    I can run the select statement just fine, i get 48 rows back. When I run with the insert statement, a total of 9062 rows are inserted. What gives?
    <SQL>
    INSERT INTO mars_aes_data
    (rpt_id, shpdt, blno, stt, shpr_nad, branch_tableS, csgn_nad,
    csgnnm1, foreign_code, pnt_des, des, eccn_no, entity_no,
    odtc_cert_ind, dep_date, equipment_no, haz_flag, schd_no,
    schd_desc, rec_value, iso_ulti_dest, odtc_exempt, itn,
    liscence_no, liscence_flag, liscence_code, mblno, mot,
    cntry_load, pnt_load, origin_state, airline_prefix, qty1, qty2,
    ref_val, related, routed_flag, scac, odtc_indicator, seal_no,
    line_no, port_export, port_unlading, shipnum, shprnm1, veh_title,
    total_value, odtc_cat_code, unit1, unit2)
    SELECT 49, schemaP.tableS.shpdt, schemaP.tableS.blno,
    schemaP.tableS.stt, schemaP.tableS.shpr_nad,
    schemaP.tableM.branch_tableS, schemaP.tableS.csgn_nad,
    schemaP.tableS.csgnnm1, schemaP.tableD.foreign_code,
    schemaP.tableS.pnt_des, schemaP.tableS.des,
    schemaP.tableD.eccn_no, schemaP.tableN.entity_no,
    schemaP.tableD.odtc_cert_ind, schemaP.tableM.dep_date,
    schemaP.tableM.equipment_no, schemaP.tableM.haz_flag,
    schemaP.tableD.schd_no, schemaP.tableD.schd_desc,
    schemaP.tableD.rec_value,
    schemaP.tableM.iso_ulti_dest,
    schemaP.tableD.odtc_exempt, schemaP.tableM.itn,
    schemaP.tableD.liscence_no,
    schemaP.tableM.liscence_flag,
    schemaP.tableD.liscence_code, schemaP.tableS.mblno,
    schemaP.tableM.mot, schemaP.tableS.cntry_load,
    schemaP.tableS.pnt_load, schemaP.tableM.origin_state,
    schemaP.tableM.airline_prefix, schemaP.tableD.qty1,
    schemaP.tableD.qty2,
    schemaC.func_getRefs@link (schemaP.tableS.ptt, 'ZYX'),
    schemaP.tableM.related, schemaP.tableM.routed_flag,
    schemaP.tableM.scac, schemaP.tableD.odtc_indicator,
    schemaP.tableM.seal_no, schemaP.tableD.line_no,
    schemaP.tableM.port_export,
    schemaP.tableM.port_unlading, schemaP.tableS.shipnum,
    schemaP.tableS.shprnm1, schemaP.tableV.veh_title,
    schemaP.tableM.total_value,
    schemaP.tableD.odtc_cat_code, schemaP.tableD.unit1,
    schemaP.tableD.unit2
    FROM schemaP.tableD@link,
    schemaP.tableM@link,
    schemaP.tableN@link,
    schemaP.tableS@link,
    schemaP.tableV@link
    WHERE tableM.answer IN ('123', '456')
    AND SUBSTR (tableS.area, 1, 1) IN ('A', 'S')
    AND entity_no IN
    ('A',
    'B',
    'C',
    'D',
    'E',
    AND TO_DATE (SUBSTR (tableM.time_stamp, 1, 8), 'YYYYMMDD')
    BETWEEN '01-Mar-2009'
    AND '31-Mar-2009'
    AND tableN.shipment= tableD.shipment(+)
    AND tableN.shipment= tableS.shipnum
    AND tableN.shipment= tableM.shipment(+)
    AND tableN.shipment= tableV.shipment(+)
    <SQL>
    Edited by: user11263048 on Jun 12, 2009 7:23 AM
    Edited by: user11263048 on Jun 12, 2009 7:27 AM

    Can you change this:
    BETWEEN '01-Mar-2009'
    AND '31-Mar-2009'To this:
    BETWEEN TO_DATE('01-Mar-2009', 'DD-MON-YYYY')
    AND TO_DATE('31-Mar-2009','DD-MON-YYYY')That may make no difference but you should never rely on implicit conversions like that, they're always likely to cause you nasty surprises.
    If you're still getting the discrepancy, instead of and INSERT-SELECT, can you try a CREATE TABLE AS SELECT... just to see if you get the same result.

  • In Oracle SQL, cannot use column in select statement and order by

    Hi,
    Is there a work around for this.
    Thanks in advance
    Pablo.

    Hi,
    943981 wrote:
    Hi All,
    This is the error I get:
    ORA-00960: ambiguous column naming in select list
    00960. 00000 - "ambiguous column naming in select list"
    *Cause:    A column name in the order-by list matches more than one select
    list columns.
    *Action:   Remove duplicate column naming in select list.
    Error at Line: 6 Column: 17That error message looks pretty clear to me. What don't you understand?
    Either
    (a) use aliases, so each column has a unique name, or
    (b) remove duplicate columns from the SELECT clause.
    Post your query. It's hard to say exactly what you're doing wrong when we don't know exactly what you're doing.
    For best results, post a complete test script (including CREATE TABLE and INSERT statements, if necessary) that people can to re-create the problem and test their ideas.
    See the forum FAQ {message:id=9360002}

  • Conditional Columns in Select Statement for any type of Report

    Okay so I had a requirement to conditionally show columns on a report when the data in the column was not null. I played around the "vertical" report mentioned in other posts but it didn't work well for my needs. Also I know that there is a javascript solution for this as demonstarted in Denes Kubicek's app (which was copied from Vikas :) ). Anyways listed below is my approach.... Hope this can help anyone else out as it's just pl/sql returning sql. Also you will need execute on dbms_sql for this to work.
    declare
    v_count number := 0;
    v_row_count number := 0;
    v_col_name varchar2(100);
    q varchar2(4000) := 'select ';
    v_table_name varchar2(100) := :SOME_TABLE_NAME;
    v_id varchar2(100) := 'num = '||:SOME_APEX_VALUE;
    my_c INTEGER;
    fdbk INTEGER;
    statement varchar2(2000);
    cval_out varchar2(2000);
    nval_out number;
    begin
    select count(*) into v_count from cols
    where table_name = v_table_name;
    for counter in 1..v_count
    loop
    select column_name into v_col_name
    from cols where table_name = v_table_name
    and counter = column_id;
    statement := 'select count(*) '||
    ' from '||v_table_name||
    ' where '||v_col_name||' is not null and '||v_id;
    my_c := dbms_sql.open_cursor;
    dbms_sql.parse(my_c,statement,dbms_sql.native);
    dbms_sql.define_column(my_c,1,nval_out);
    fdbk := dbms_sql.execute(my_c);
    LOOP
    exit when dbms_sql.fetch_rows(my_c) = 0;
    dbms_sql.column_value(my_c,1,nval_out);
    end loop;
    v_row_count := nval_out;
    dbms_sql.close_cursor(my_c);
    if v_row_count > 0 then
    q:=q||v_col_name||',';
    end if;
    end loop;
    if(substr(q,length(q),1) = ',') then
    q:= substr(q,0,length(q)-1);
    end if;
    q:= q||' from '||v_table_name||' where '||v_id;
    end;Hope this helps...
    -David
    Message was edited by:
    rdpatric

    Hi Gints,
    Thank you for your reply. This is my query and
    nvl(TICKET_JOIN.TDQRLV,0) ACC_SHIPPED_QTY,
    TICKET_JOIN.TDSOQS QUANTITY_TICKETED are the columns tha's creating issue. If I comment those columns Index is accessed properly.
    select
    'TKT' SOURCE,
    TICKET_JOIN.TKDO01 HIRE_ID,
    TICKET_JOIN.TKQ101 TRUCK_ID,
    TICKET_JOIN.TKVEHT TRUCK_TYPE,
    1 TRUCK_COMM,
    nvl(TKCMP1,0) TICKET_NUM,
    nvl(TKADTM,0) TICKET_TIME,
    --TICKET_JOIN.TDSOQS QUANTITY_TICKETED,
    0 CHECKIN_TIME,
    --nvl(TICKET_JOIN.TDQRLV,0) ACC_SHIPPED_QTY,
    nvl(DDADTM,0) START_TIME
    from
    (select
    TICKET.TKCMP1,
    TICKET.TKDO01,
    TICKET.TKQ101,
    TICKET.TKADTM ,
    TICKET.TKVEHT,
    TICKET_DETAILS.TDAITM ,
    TICKET_DETAILS.TDQRLV ,
    TICKET_DETAILS.TDSOQS ,
    TICKET.TKCNTF,
    TICKET.TKTRDJ,
    TICKET.TK58GA8
    from
    CRPDTA.F5800091 TICKET_DETAILS ,
    CRPDTA.F5800090 TICKET
    where TICKET.TKCMP1 = TICKET_DETAILS.TDCMP1
    and TICKET.TKTRDJ = TICKET_DETAILS.TDTRDJ
    and TICKET.TKTRDJ = 107085
    and TICKET.TKEV12 <> 'Y'
    and TICKET.TK58GA8='ECSEO'
    and TICKET.TKCNTF = '11') TICKET_JOIN ,
    (select
    DDDOCO,
    DDCNTF,
    DDQTFN,
    DDAITM,
    DDADTM,
    DD58GA8,
    DDTRDJ
    from
    CRPDTA.F5800051 ORDER_DETAILS,
    CRPDTA.F5800050 ORDER_HEADER
    where
    ORDER_HEADER.DHDOCO = ORDER_DETAILS.DDDOCO
    and ORDER_HEADER.DHTRDJ = ORDER_DETAILS.DDTRDJ
    and ORDER_HEADER.DH58GA8 = ORDER_DETAILS.DD58GA8
    and ORDER_HEADER.DHDCTO = ORDER_DETAILS.DDDCTO
    /*and
    (ORDER_HEADER.DHTRDJ = 107085
    OR (ORDER_HEADER.DHTRDJ = 107084 and ORDER_HEADER.DHEV04='Y')
    and TRIM(ORDER_HEADER.DH58GA8) = 'ECSEO'
    and TRIM(ORDER_DETAILS.DDCNTF) = '11' ) ORDER_VIEW
    where TICKET_JOIN.TKTRDJ = ORDER_VIEW.DDTRDJ
    and TICKET_JOIN.TDAITM = ORDER_VIEW.DDAITM
    and TICKET_JOIN.TKCNTF = ORDER_VIEW.DDCNTF
    and TICKET_JOIN.TK58GA8 = ORDER_VIEW.DD58GA8
    and NOT EXISTS ( select 1 from CRPDTA.F5800120 TRUCK_ASSIGNMENT
    where TATRDJ = 107085
    and TACNTF = '11'
    and TA58GA8 = 'ECSEO'
    and TICKET_JOIN.TKQ101||TICKET_JOIN.TKVEHT = TAQ101||TAVEHT )
    Thanks
    GM

  • Sort key too long - maximum number of columns in select statement

    the sort key too long is caused by either too many group
    functions or too many columns selected. Does anyone know the
    maximum number of columns that can be selected in one statement ?

    The Oracle 9i reference states ...
    The GROUP BY expression and all of the
    nondistinct aggregates functions (for example,
    SUM, AVG) must fit within a single database
    block.
    ... and the Oracle 9i SQL Reference states that ...
    An order_by_clause can contain no more than 255
    expressions.
    You could check your own documentation, but i think it will
    be the same.

  • Grouping by a single column of select statement to set status

    Hi,
    I need a help in getting the o/p in a single SQL statement.
    I have the below scenario:
    Part_No Event Indic     --Status
    A     E1     X     
    A     E2     Y     
    A     E3     N     --Null
    B     C1     Y     
    B     C2     Y
    B     C3     Y     --Listed
    C     D1     Null
    C     D2     Y
    C     D3     Y     ---Unknown
    I need to derive the status as shown above:
    1. "Listed" when all Events has Indic as Y
    2. "Unlisted" when atleast one Event has Indic as N
    3. "Unknown" when atleast one Event has X or Null
    I wanted the result like given below:
    Part_No          Status
    A          Null
    B          Listed
    C          Unknown
    Please help me get this in a single SQL statment
    Thanks
    SaintelE

    Hi,
    Please let me know if the below is elaborative:
    I need a help in setting the status based on the values given below in a table.
    Say for example, I have the below rows in a table : column names: Part_No, Event, Indic
    I need to derive the Status as "Unlisted", "Listed", "Unknown" using Case statement:
    Part_No Event Indic     --Status
    A     E1     X     
    A     E2     Y     
    A     E3     N     --Unlisted
    B     C1     Y     
    B     C2     Y
    B     C3     Y     --Listed
    C     D1     Null
    C     D2     Y
    C     D3     Y     --Unknown
    I need to derive the Status value as
    1. "Listed" only when all Events (E1, E2, E3) has Indic as Y,
    2. "Unlisted" only when atleast one Event has Indic as N
    3. "Unknown" only when atleast one Event has "X" or Null
    I wanted the result like given below by grouping by Part_No:
    Part_No          Status
    A          Null
    B          Listed
    C          Unknown
    Please help me get this in a single SELECT statment
    Thanks
    SaintelE

Maybe you are looking for