Help in sub query

Hi all,
I have a problem in writing queries in order to get a value as a single row
this is how my table as values
site_no falg1 flag2 flag3
1 Y Y Y
1 Y N Y
2 Y N N
I wrote 8 subqeries with eight different conditions and retrieved the site_no something like
select site_no from table where flag1=Y and flag2=Y and Flag3=Y.
Like this I wrote eight subqueries and got the sitenumbers.
How do i join these queries and get a single site_no?
I can't put equi join... Also I have a common table containing all these site_nos...
can any one help me in this?
Please let me know if you need more information on this.

This is my subquery
SELECT H.ORDER_SITE_NO
,COUNT(D.ORDER_ID) linecount
,sum(DECODE(d.BACKORDER_FL,'Y',1,'N',0)) as BCOUNT
,(sum(DECODE(d.BACKORDER_FL,'Y',1,'N',0))/COUNT(D.ORDER_ID)) * 100 as BCOUNTpct
FROM
DBO.OTR_M_PQMOD_TPS MP,
DBO.OTR_LOCITEM_TPS L,
DBO.OTR_ITEMUPC_PBS IU,
DBO.OTR_ORDER_DTL_PBS d,
DBO.OTR_ORDER_HDR_PBS h
Where
MP.MODEL_NUM = L.ITEM_NUM
and d.Actual_Delivery_Dt <= :gprmDeliveryEndDate
and d.ORDER_SITE_NO = TO_NUMBER(L.SITE_NUM)
AND IU.UPC_ID = RTRIM(L.ITEM_NUM)
and iu.SKU_NO = d.SKU_NO
and d.ORDER_SITE_NO = h.ORDER_SITE_NO
and d.ORDER_ID = h.ORDER_ID
and mp.IS_NONIVENTORIED = 'N'
and L.SITE_NUM <> '*ALL'
AND IU.UPC_SEQ = 1
and d.qty > 0
and d.STATUS_CD = 'CL'
and h.ORDER_NOTES not like 'External%'
and L.IS_STOCK ='Y'
and L.AUTO_REPLEN ='Y'
and MP.LOCAL_ITEM='Y'
GROUP BY
H.ORDER_SITE_NO
Like this i have 7 more queries with different values for IS_STOCK and AUTO_REPLN and LOCAL_ITEM
if the subquery1 pulls siteno 1 its not necessary that subquery will pull siteno 1 it may or maynot pull.
but i want this 1 in my result set

Similar Messages

  • How to rewrite this query without sub query please help me

    Hello All Good Evening,
    Could you please help me with this query, how can i write this query without sub query, or how can write this query another ways
    please help me
    select planno, status1, count(*) Counts from
    select a.ValetNO PlanNo  ,
    case 
         when JoinCode in ('00', '01', '02') then 'Actcess'
         when JoinCode in ('20', '21', '22', '23','38', '39') then
         'Secured' else 'Other' end Status1 ---, COUNT (*)
       from  dbo.ppt a(NOLOCK)  left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO  = b.ValetNO
    --group by a.ValetNO
      a group by planno, status1
    order by 2
    Thank you in Advance
    Milan

    Whats your objective here? Sorry, am not able to understand the reason for this change. 
    Try the below:(Not tested)
    ;With cte
    As
    select a.ValetNO PlanNo ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end Status1 ---, COUNT (*)
    from dbo.ppt a(NOLOCK) left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO = b.ValetNO
    select planno, status1, count(*) Counts from cte
    a group by planno, status1
    order by 2
    Even below:
    select a.ValetNO PlanNo ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end Status1 , COUNT (1)
    from dbo.ppt a(NOLOCK) left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO = b.ValetNO
    Group by a.ValetNO ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end

  • Hi! Everyone, I have some problems with JOIN and Sub-query; Could you help me, Please?

    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!

    Hi,
    fac30d8e-74d3-42aa-b643-e30a3780e00f wrote:
    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!
    As the others have said, the execution plan will give you a better idea about which is faster.
    If you're trying to see how using (or not using) a sub-query affects performance, make the rest of the queries as similar as possible.  For example, include field3 in both queries, or ignore field3 in both queries.
    In this particular case, I guess the optimizer would do the same thing either way, but that's just a guess.  I can't see your execution plans.
    In general, simpler code is faster, and better in other ways, too.  In this case
    tableB
    is simpler than
    (SELECT field1, field2  FROM tableB)
    Why do you want a sub-query in this example?

  • Can someone please help me with a sub query question?

    I need to list a 3rd party contract and then a list of students who belong to that contract.
    On the students segment of the listing I need to show students with student id, name, total credit hours,
    total amount spent on tuition, total amount spent on books and total amount spent on misc.
    This code has a query for the contract information and I get that just fine.
    Then it has a query that gives me total credit hours and that works fine
    then it has a query that gives me total amount spent on tuition and that works fine
    but
    when I add the next query to get total amount spent on books I get only the information for the contract, I don't get student stuff anymore.
    I would really appreciate any guidance that you could give.
    Thanks in advance, Bob Hohulski
    DECLARE
    l_conn utl_TCP.connection;
    v_filehandle utl_file.file_type;
    v_output varchar2(1000);
    v_contract_id varchar2(9);
    v_contract_addr1 varchar2(30);
    v_contract_addr2 varchar2(30);
    v_contract_city varchar2(20);
    v_contract_stat varchar2(03);
    v_contract_zip varchar2(10);
    v_contract_name varchar2(60);
    v_student_id varchar2(09);
    v_student_first_name varchar2(15);
    v_student_mid_name varchar2(15);
    v_student_last_name varchar2(60);
    v_last_out varchar2(20);
    v_student_detail_code varchar2(04);
    v_student_amount number(12,2);
    v_student_ref_number varchar2(09);
    v_credit_hrs number(7,2);
    v_tuition_amount number(12,2);
    v_books_amount number(12,2);
    v_misc_amount number(12,2);
    v_total_for_student number(12,2);
    v_current_student varchar2(09);
    v_sftregs_pidm varchar2(09);
    v_tbraccd_pidm varchar2(09);
    CURSOR c_sel_contract IS
    SELECT DISTINCT spriden_id, spriden_last_name,
    spraddr_street_line1, spraddr_street_line2,
    spraddr_city, spraddr_stat_code, spraddr_zip
    FROM spriden, spraddr
    -- WHERE spriden_id = '&Enter_Id'
    where spriden_id = 'T10474666'
    AND spriden_pidm = spraddr_pidm
    AND SPRIDEN_CHANGE_IND IS NULL;
    CURSOR c_sel_student IS
    SELECT DISTINCT spriden_id, spriden_first_name, spriden_mi, spriden_last_name,
    sftregs_credit_hr,
    tbraccd_amount,
    sftregs_pidm,
    tbraccd_pidm
    FROM spriden, tbraccd, tbbcstu, sftregs
    WHERE 559220 = tbbcstu_contract_pidm
    AND spriden_pidm = tbraccd_pidm
    AND spriden_pidm = tbbcstu_stu_pidm
    AND spriden_pidm = sftregs_pidm
    AND (sftregs_pidm, sftregs_credit_hr) IN
    (SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
    FROM sftregs, tbbcstu, spriden
    WHERE sftregs_term_code = '201010'
    AND sftregs_pidm = tbbcstu_stu_pidm
    AND sftregs_pidm = spriden_pidm
    GROUP BY sftregs_pidm)
    AND (tbraccd_pidm, tbraccd_amount) IN
    (SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
    -- tuition
    FROM tbraccd, tbbcstu, spriden
    WHERE tbraccd_term_code = '201010'
    AND (tbraccd_detail_code = 'TU01' OR
    tbraccd_detail_code = 'TU02' OR
    tbraccd_detail_code = 'TU03' OR
    tbraccd_detail_code = 'TU04')
    AND tbraccd_pidm = tbbcstu_stu_pidm
    AND tbraccd_pidm = spriden_pidm
    GROUP BY tbraccd_pidm)
    --this code works up to this point
    --when I add the next query I get nothing
    AND (tbraccd_pidm, tbraccd_amount) IN
    (SELECT tbraccd_pidm, SUM(tbraccd_amount)
    books
    FROM tbraccd, tbbcstu
    WHERE tbraccd_term_code = '201010'
    AND (tbraccd_detail_code = 'BKSU' OR
    tbraccd_detail_code = 'BKCH')
    AND tbraccd_pidm = tbbcstu_stu_pidm
    GROUP BY tbraccd_pidm, tbraccd_amount)
    --AND (tbraccd_pidm, tbraccd_amount) IN
    -- (SELECT tbraccd_pidm, SUM(tbraccd_amount)
    -- misc
    -- FROM tbraccd, tbbcstu
    -- WHERE tbraccd_term_code = '201010'
    -- AND tbraccd_pidm = tbbcstu_stu_pidm
    -- AND (tbraccd_detail_code = 'AUNA' OR
    -- tbraccd_detail_code = 'OTPB')
    -- GROUP BY tbraccd_pidm, tbraccd_amount)
    --ORDER BY tbraccd_pidm, spriden_first_name, spriden_mi, spriden_last_name,
    -- tbbcstu_sponsor_ref_number, sftregs_credit_hr;
    ORDER BY tbraccd_pidm;
    BEGIN
    v_filehandle := utl_file.fopen(location => 'UTLFILE_MISAP9',
    filename => 'ban_matrix.dat',
    open_mode => 'w',
    max_linesize => 32767);
    OPEN c_sel_contract;
    LOOP
    DBMS_OUTPUT.PUT_LINE('looping');
    FETCH c_sel_contract INTO v_contract_id, v_contract_name,
    v_contract_addr1, v_contract_addr2,
    v_contract_city, v_contract_stat,
    v_contract_zip;
    EXIT WHEN c_sel_contract%NOTFOUND;
    v_output :=
    nvl(rpad(v_contract_id,9),rpad(' ',9)) ||
    ' ' ||
    nvl(rpad(v_contract_name,60),rpad(' ',60));
    utl_file.put_line(v_filehandle,v_output);
    v_output :=
    nvl(rpad(v_contract_addr1, 30),rpad(' ',30)) ||
    ' ' ||
    nvl(rpad(v_contract_addr2, 30),rpad(' ',30));
    utl_file.put_line(v_filehandle,v_output);
    v_output :=
    nvl(rpad(v_contract_city, 20), rpad(' ',20)) ||
    ' ' ||
    nvl(rpad(v_contract_stat, 3), rpad(' ',3)) ||
    ' ' ||
    nvl(rpad(v_contract_zip, 10), rpad(' ',10));
    utl_file.put_line(v_filehandle,v_output);
    utl_file.new_line(v_filehandle);
    OPEN c_sel_student;
    LOOP
    FETCH c_sel_student into v_student_id, v_student_first_name, v_student_mid_name,
    v_student_last_name,
    v_credit_hrs,
    v_tuition_amount,
    v_sftregs_pidm,
    v_tbraccd_pidm;
    -- v_books_amount, v_misc_amount;
    EXIT WHEN c_sel_student%NOTFOUND;
    v_last_out := substr(v_student_last_name, 1, 20);
    v_output :=
    nvl(rpad(v_student_id, 09),rpad(' ',09)) ||
    ' ' ||
    nvl(rpad(v_student_first_name, 15),rpad(' ',15)) ||
    nvl(rpad(v_student_mid_name, 15),rpad(' ',15)) ||
    nvl(rpad(v_last_out, 20),rpad(' ',20)) ||
    ' ' ||
    nvl(rpad(v_student_ref_number, 09),rpad(' ',09)) ||
    ' ' ||
    v_credit_hrs ||
    ' ' ||
    v_tuition_amount ||
    -- v_books_amount ||
    -- ' ' ||
    -- v_misc_amount;
    utl_file.put_line(v_filehandle,v_output);
    END LOOP;
    END LOOP;
    --EXCEPTION
    --WHEN OTHERS THEN
    -- DECLARE
    -- err_msg VARCHAR2(100);
    -- BEGIN
    -- err_msg := 'ERR- '||SUBSTR(SQLERRM, 1,100);
    -- - utl_file.put_line(v_filehandle,err_msg);
    --END;
    utl_file.fclose(v_filehandle);
    CLOSE c_sel_contract;
    CLOSE c_sel_student;
    --END AR_MATRIX_PROC;
    END;

    run this original query
    SELECT DISTINCT spriden_id,
            spriden_first_name,
            spriden_mi,
            spriden_last_name,
            sftregs_credit_hr,
            tbraccd_amount,
            sftregs_pidm,
            tbraccd_pidm
       FROM spriden, tbraccd, tbbcstu, sftregs
    WHERE 559220 = tbbcstu_contract_pidm
       AND spriden_pidm = tbraccd_pidm
       AND spriden_pidm = tbbcstu_stu_pidm
       AND spriden_pidm = sftregs_pidm
       AND (sftregs_pidm, sftregs_credit_hr) IN (SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
                                                   FROM sftregs, tbbcstu, spriden
                                                  WHERE sftregs_term_code = '201010'
                                                    AND sftregs_pidm = tbbcstu_stu_pidm
                                                    AND sftregs_pidm = spriden_pidm
                                                 GROUP BY sftregs_pidm)
       AND (tbraccd_pidm, tbraccd_amount) IN (SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
                                              -- tuition
                                                FROM tbraccd, tbbcstu, spriden
                                               WHERE tbraccd_term_code = '201010'
                                                 AND (tbraccd_detail_code = 'TU01' OR
                                                      tbraccd_detail_code = 'TU02' OR
                                                      tbraccd_detail_code = 'TU03' OR
                                                      tbraccd_detail_code = 'TU04')
                                                 AND tbraccd_pidm = tbbcstu_stu_pidm
                                                 AND tbraccd_pidm = spriden_pidm
                                               GROUP BY tbraccd_pidm)
       AND (tbraccd_pidm, tbraccd_amount) IN (SELECT tbraccd_pidm, SUM(tbraccd_amount) books
                                                FROM tbraccd, tbbcstu
                                               WHERE tbraccd_term_code = '201010'
                                                 AND (tbraccd_detail_code = 'BKSU' OR
                                                      tbraccd_detail_code = 'BKCH')
                                                 AND tbraccd_pidm = tbbcstu_stu_pidm
                                              GROUP BY tbraccd_pidm, tbraccd_amount)
    ORDER BY tbraccd_pidm;then run this sub-query:
    SELECT tbraccd_pidm, SUM(tbraccd_amount) books
       FROM tbraccd, tbbcstu
      WHERE tbraccd_term_code = '201010'
        AND (tbraccd_detail_code = 'BKSU' OR
             tbraccd_detail_code = 'BKCH')
       AND tbraccd_pidm = tbbcstu_stu_pidm
    GROUP BY tbraccd_pidm, tbraccd_amount)see if you have a matching tbraccd_pidm and tbraccd_amount between the two results.

  • Help with doing SELECT sub query within the SET of an UPDATE statement

    After doing some research, it appears as if it's possible to use a SELECT subquery in the SET of an UPDATE statement.  i did find some examples and here is my code, however when I click the "check" button it's saying the field (my entire select subquery) is unknown and neither in one of the specified tables or defined by a "DATA".  Do I have a syntax issue or is there another reason why it's not taking this as a valid statement?  Thanks for the help!
    LOOP AT IT_DATA
    UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL )
                            FROM /BIC/AZDP_O0140
                            WHERE MATERIAL EQ IT_DATA-MATERIAL
                            GROUP BY MATERIAL).
    ENDLOOP.

    my Update does indeed have a WHERE clause but because of the issue i'm having, all my criteria in my WHERE is black text in the ABAP editor.  The editor doesn't even recognize the keywords "WHERE" or "EQ".  Below is my entire statement which contains all WHERE criteria in both the Update and the Subquery, i've just removed it for testing to help simplify the query and eliminate as many other factors as posisble that may be causing problems:
    LOOP AT IT_DATA.
       UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL ) FROM /BIC/AZDP_O0140
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL
        GROUP BY MATERIAL)
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL.
    ENDLOOP.
    i should also mention the sources i found were not within the SAP Library but instead on other third-party ABAP websites.  so because i was having issues i wanted to post here to see if anyone else has come up with a working solution.  but if this cannot be done i can likely come up with a solution for my needs using multiple internal tables, this would just have been much easier since i can get a query like this to do what i want in SQL Server.  Thought i could utilize this in ABAP as well.

  • Help on Converting inerr query to sub query

    Hi Guys,
    This query is written in inner join, can any one try to write using sub query.
    SELECT B.CNO
    FROM CUSTEN A
    INNER JOIN ORDS B
    ON A.CNO = B.CNO
    AND A.PRNO = B.PRNO
    INNER JOIN ORDI C
    ON B.ORDNO = C.ORDNO
    INNER JOIN PRD D
    ON C.PRNO = D.PRNO
    WHERE B.STS = 'COM'
    AND B.LMD >= A.LMD
    GROUP BY B.CSTNO, C.PRNO
    HAVING COUNT(B.ORDNO) > 1
    Thanks in advance!
    Regards,
    LKRao
    Edited by: kolipaka on Sep 18, 2012 6:37 PM
    Edited by: kolipaka on Sep 18, 2012 6:38 PM

    Hi,
    kolipaka wrote:
    Hi Guys,
    This query is written in inner join, can any one try to write using sub query. Why?
    We don't know your requirements, so we can't be sure if any solution we might think of meets your requirements.
    ... GROUP BY B.CSTNO, C.PRNOIf you really need to GROUP BY columns from different tables, then you almost certainly want to join those tables. You might be able to get the results you want with a scalar sub-query instead of a join, but that's needlessly complicated.
    You said that what you posted is just a sub-query of some other query. Perhaps the solution involves making changes in that query, too. Post the complete query, CREATE TABLE and INSERT statments for a little sample data, the results you want from that data, and an explanation of how you get those results from that data. Say which columns are unique (expecially the columns used in the join conditions); that could be important.

  • How to use sub query in CAML in splist

    hi,
    want to know whether any sub query functionality can be achieved in splist/sp doc lib using  CAML designer 2013/ query builder. also inner joins need to be implemented as pe rmy requirement.
    if caml designer is not supported, whats the allternative way of doing this?
    can LINQ to SP be used? if yes, can anyone pls roivde how to implement  the same
     help is appreciated

    You can use the let keyword to scope a variable containing the result of your subquery.
     However, it depends on the LINQ provider as to whether or not it can understand the command.
    For example, you can create the sample like this
    var result = (from p in productInQuery
          join o in orderInfoQuery on p.refNo equals o.refNo
          join t in productOutQuery on p.no equals t.productInNo into productIn
          from t in productIn.DefaultIfEmpty()
          let dateOut = (from m in orderInfoQuery where m.refNo == t.refNo select m.processData).FirstOrDefault()
          orderby o.processDate descending
          select new
              modelNo = x.modelNo,
              qty = p.qty,
              dateIn = o.processDate,
              dateOut = dateOut
    https://www.youtube.com/watch?v=N3K0h6GDwW4
    For more info, check this
    http://msdn.microsoft.com/en-us/library/ee539975.aspx

  • Possibility of launch of  a sub query in a query

    Hi developers,
    I have an urgent problem! I have created a query to calculate with a formula an indicator but if I effectue a drill down for customer I have a correct result while when I drill down for country the rows compact the value and the result change in wrong. Is There the possibility or a functionality who allows the launch of a query with selection on another query.
    Have Someone a solution to this problem ?
    Thanks,
    Domeico
    Message was edited by: Domenico Manti

    Hi Domeico,
    I'm not sure I understand your problem correctly, but instead of launching a sub query in a query I would recommend to check, whether a variable with replacement path (reference to characteristic (constant 1)) might solve your problem.
    http://help.sap.com/saphelp_nw04/helpdata/en/03/6ba03cc24efd1de10000000a114084/frameset.htm
    and
    http://help.sap.com/saphelp_nw04/helpdata/en/ca/5f9ac61a205a459d0e7ef313d10321/frameset.htm
    Heike

  • Doubt in sub-query

    I have a doubt with the use of sub-queries. I am using a query like as below & it is giving me expected result:-
    SELECT ISS.item_type_id,count(1) + (select sum(invoiced_qty) from ppbs_invoice_detail where
    trunc(created_date) between '01-jul-05' and '04-jul-05' and item_type_id=ISS.item_type_id) qty
    FROM ppbs_INV_SIM_SERIAL ISS
    WHERE INSTR('ROAAIT',STATUS)>0
    AND INSTR('NU0NU1NU2NU3SC0',CITY_CODE) =0
    and ISS.item_type_id in ('SM17')
    group by ISS.item_type_id --
    I will re-write above query & i have been using queries like :-
    SELECT ISS.item_type_id,count(1) qty
    FROM ppbs_INV_SIM_SERIAL ISS
    WHERE INSTR('ROAAIT',STATUS)>0
    AND INSTR('NU0NU1NU2NU3SC0',CITY_CODE) =0
    and ISS.item_type_id in ('SM17') and item_type_id in
    (select item_type_id from ppbs_invoice_detail where
    trunc(created_date) between '01-jul-05' and '04-jul-05' and item_type_id=ISS.item_type_id)
    group by ISS.item_type_id
    my doubt here is that the sub-query in the first query is coming before i use the table 'ppbs_inv_sim_serial ISS' whereas in the second query, the table use 'ppbs_inv_sim_serial ISS' is coming before the sub-query use. I have been using queries where table name is defined before the sub-query.
    I hope, my question is clear. Please help in solving the doubt.
    Regards.

    I don't see a problem with the table aliasing that you seem to doubt, but your first query won't run. I boiled the thing down to basics: SQL>create table t1 (one number, val_1 number );
    Table created.
    SQL>create table t2 (one number, val_2 number );
    Table created.
    SQL>insert into t1 values (1,1);
    1 row created.
    SQL>insert into t2 values (1,2);
    1 row created.
    SQL>select a.one, count(1) + ( select sum(val_2) from t2 where t2.one = a.one) qty
      2  from  t1 a
      3  group by one;
    select a.one, count(1) + ( select sum(val_2) from t2 where t2.one = a.one) qty
    ERROR at line 1:
    ORA-00979: not a GROUP BY expression
    SQL>
    SQL>select a.one, count(1) qty
      2  from   t1 a
      3  where  a.one in ( select one from t2 where one = a.one)
      4  group by one;
           ONE        QTY
             1          1It's superfluous to "where a.one in ( select.. where = a.one) but that's your code basically. I would just do "="

  • Joining with sub query not working

    Hi
    I am new with these complex queries. I am trying to join a sub query to a query as below;
    SELECT Events1.InvoiceBatch AS BatchNo, Events1.InvoiceBatchDate AS BatchDate, tblClients.Company, tblClients.ID AS ClientID, COUNT(Events1.ID) AS Invoices,
    COUNT(*) - COUNT(Events1.InvoicePrintDate) AS E, Events1.InvoiceBatchFromDate AS BatchFrom, Events1.InvoiceBatchToDate AS BatchTo, (SELECT EventID, SUM(Total) FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) AS Total
    FROM tblEvents AS Events1 LEFT OUTER JOIN
    tblClients ON Events1.ClientID = tblClients.ID
    WHERE (Events1.FactoringExportDate IS NULL) OR (Events1.AccountsExportDate IS NULL) OR (Events1.InvoiceSentDate IS NULL)
    GROUP BY Events1.InvoiceBatch, Events1.InvoiceBatchDate, tblClients.Company, tblClients.ID, Events1.InvoiceBatchFromDate, Events1.InvoiceBatchToDate
    HAVING (Events1.InvoiceBatch = 5212)
    ORDER BY tblClients.Company
    I am getting these two errors;
    Msg 8120, Level 16, State 1, Line 2
    Column 'tblEvents.ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
    Msg 116, Level 16, State 1, Line 2
    Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
    What am I missing?
    Thanks
    Regards

    SELECT Events1.InvoiceBatch AS BatchNo, Events1.InvoiceBatchDate AS BatchDate, tblClients.Company, tblClients.ID AS ClientID, COUNT(Events1.ID) AS Invoices,
    COUNT(*) - COUNT(Events1.InvoicePrintDate) AS E, Events1.InvoiceBatchFromDate AS BatchFrom, Events1.InvoiceBatchToDate AS BatchTo,Total
    FROM tblEvents AS Events1 LEFT OUTER JOIN
    tblClients ON Events1.ClientID = tblClients.ID
    LEFT OUTER JOIN (SELECT EventID, SUM(Total) AS Total FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) sb
    ON sb.EventID = Events1.ID
    WHERE (Events1.FactoringExportDate IS NULL) OR (Events1.AccountsExportDate IS NULL) OR (Events1.InvoiceSentDate IS NULL)
    GROUP BY Events1.InvoiceBatch, Events1.InvoiceBatchDate, tblClients.Company, tblClients.ID, Events1.InvoiceBatchFromDate, Events1.InvoiceBatchToDate,Total
    HAVING (Events1.InvoiceBatch = 5212)
    ORDER BY tblClients.Company
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page
    Says;
    Msg 4104, Level 16, State 1, Line 5
    The multi-part identifier "Events1.ID" could not be bound.
    on
    LEFT OUTER JOIN (SELECT EventID, SUM(Total) AS Total FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) sb
    Regards

  • Use of Sub Query in a filter is throwing error

    Hi
    I am using a sub query in a filter which throws me the following error in owb 9i.
    PLS 00405 : Subquery cannot be used in this context.
    But the use of subquery works fine in a joiner operator.
    Use of Sub Query in a filter works fine in owb 2i.
    Could any one please help me.
    Thanks in Advance
    Nanda Kishore

    Nanda,
    Please wrap the source table in a view containing the subquery and then use the view as a source rather than use the subquery in the filter.
    Regards:
    Igor

  • How do you get a Sub Query in a Mapping

    Hi, I am wanting to know how or what the work around is for getting a Sub query in a join operator?
    Its a really common place thing to do, I need to add an where exists or not exists type clause to one of my mapping joins.
    Can someone please advise how this can be done using OWB.
    Thanks,
    Richard.

    I'm interested too.
    Please help, I had own method to management  iCal's event – new line, of 10.7 worked great – now is a little terrible for me :/

  • The issue with using the multiple columns sub-query in WHERE clause

    Hi All,
    my database version is 10.2.
    the problem i am trying to deal with is that when I use multiple column sub-query in the WHERE clause of the SELECT statement, the actual row number returned from the sub-query is different from the whole statement.
    And what I found is that, whenever there is NULL in any of those columns returned from the SUB-QUERY, the outer query will just return NULL for that whole row.
    Here is an example:
    select empno, ename, job, mgr, hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  mgr, hiredate, sal, deptno from t;
    7782     CLARK     MANAGER     7839     09-JUN-81     2450     10
    7839     KING     PRESIDENT  NULL  17-NOV-81     5000     10
    7934     MILLER     CLERK     7782     23-JAN-82     1300     10
    select * from EMP where (EMPNO, ENAME, job, MGR, HIREDATE, SAL, DEPTNO) in (
    select empno, ename, job, mgr, hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  mgr, hiredate, sal, deptno from t);
    7782     CLARK     MANAGER     7839     09-JUN-81     2450          10     
    7934     MILLER     CLERK     7782     23-JAN-82     1300          10     If I specifically deal with the NULL situations for the columns which might return NULL, I can get the result right.
    select * from EMP where (EMPNO, ENAME, job, NVL(MGR,-1), HIREDATE, SAL, DEPTNO) in (
    select empno, ename, job, nvl(mgr,-1), hiredate, sal, deptno from EMP
    intersect
    select empno, ename, job,  nvl(mgr,-1), hiredate, sal, deptno from t);
    7782     CLARK     MANAGER     7839     09-JUN-81     2450          10     
    7839     KING     PRESIDENT  null   17-NOV-81     5000          10     
    7934     MILLER     CLERK     7782     23-JAN-82     1300          10     the problem is that, I feel this is a very lame way of handling it.
    So, I wonder or am asking if there is any better or standard way to do it?
    any help would be highly appreciated.
    Thanks

    Hi,
    As you discovered, INTERSECT treats NULL as a value, but IN does not.
    What you did with NVL is one way to handle the situation. If there was a chance that any of the columns could be NULL, then you might prefer something like this:
    select      *
    from      EMP
    where      ( EMPNO      || '~' ||
           ENAME      || '~' ||
           job           || '~' ||
           MGR           || '~' ||
           TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')
                    || '~' ||
           SAL           || '~' ||
           DEPTNO
         ) in (
              select  EMPNO      || '~' ||
                     ENAME      || '~' ||
                   job     || '~' ||
                   MGR     || '~' ||
                   TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')               
                        || '~' ||
                   SAL      || '~' ||
                   DEPTNO
              from     emp
             intersect
              select  EMPNO      || '~' ||
                     ENAME      || '~' ||
                   job     || '~' ||
                   MGR     || '~' ||
                   TO_CHAR (HIREDATE, 'DD-MON-YYYY HH24:MI:SS')               
                        || '~' ||
                   SAL      || '~' ||
                   DEPTNO
              from      t
             );This assumes that you can identify some string (I used '~') that never occurs in the strings in these tables.
    This is implicitly converting the NUMBERs. That's usually not a good thing to do. but explicitly converting them would make this even more tedious.
    You should explicitly convert any DATEs to strings, however. Depending on your default format, and your data, you might get away with implicit conversions even for DATEs, but don't bet on it.
    If you had to do this often, you might consider writing a user-defined function:
    delimited_string (empno, ename, job, mgr, hiredate, sal, deptno) would return a string like
    '7839~KING~PRESIDENT~~17-NOV-1981~5000~10'
    This will make the coding easier, but beware: it will make the execution slower.

  • Need help with the query -

    We have these two tables and trying to see if the amount in one table is equal to the sum of the amount fields in another table.
    Can someone please help?
    SQL> desc test;
    Name Null? Type
    KEY NUMBER(9)
    AMOUNT NUMBER(11,2)
    SQL> desc test1;
    Name Null? Type
    KEY NUMBER(9)
    TOTAL_AMOUNT NUMBER(11,2)
    SQL> select * from test;
    KEY AMOUNT
    1 10
    1 20
    1 70
    3 rows selected.
    SQL> select * from test1;
    KEY TOTAL_AMOUNT
    1 100
    1 row selected.
    SQL> select count(*) from test1 a where exists(select 'x' from test b where
    2 a.key=b.key and a.total_amount!=sum(b.amount));
    a.key=b.key and a.total_amount!=sum(b.amount))
    ERROR at line 2:
    ORA-00934: group function is not allowed here

    Hi,
    This would be so easy if there was a table like test that only had one row per key!
    You can make such a table, or you can just make a sub-query that has all the same data, and use that sub-query as if it were a table.
    For example:
    WITH  one_row_per_key_test  AS
        SELECT    key
        ,         SUM (amount)  AS total_amount
        FROM      test
        GROUP BY  key
    SELECT  COUNT (*)
    FROM    test1   a
    WHERE   EXISTS
            SELECT  'x'
            FROM    one_row_per_key_test  b
            WHERE   a.key          = b.key
            AND     a.total_amount = b.total_amount
            );There are lots of other ways to solve this particular problem (including HAVING), but this is a very important technique to know.

  • SELECT records larger than date specified in sub query

    Dear All
    Thank you for your attention.
    I would like to select records larger than date specified in sub query
    query should be something like the following
    SELECT my_order_number, my_date, my_task
    FROM MYTB
    WHERE my_order_number IN order_no AND my_date > date (SELECT order_no, date FROM MySubQueryResult)
     (it is incorrect)
    Sub query result:
    order_no | date
    A1    | 2014-12-21 09:06:00
    A2    | 2014-12-20 09:07:00
    A3    | 2014-12-20 08:53:00
    A4    | 2014-12-20 08:57:00
    MYTB:
    my_order_number | my_task | my_date
    A1  |  T1  |  2014-12-21 09:06:00
    A1  |  T2  |  2014-12-22 10:01:00
    A2  |  T1  |  2014-12-20 09:07:00
    A3  |  T2  |  2014-12-20 08:53:00
    A3  |  T4  |  2014-12-21 09:30:00
    A3  |  T8  |  2014-12-23 20:32:00
    A4  |  T6  |  2014-12-20 08:57:00
    expected result:
    my_order_number |  my_task | my_date
    A1  |  T2  |  2014-12-22 10:01:00
    A3  |  T4  |  2014-12-21 09:30:00
    A3  |  T8  |  2014-12-23 20:32:00
    Any ideas?  Thanks.
    swivan

    Hi,
    try this
    SELECT my_order_number, my_date, my_task
    FROM MYTB
    WHERE my_order_number IN (SELECT order_no FROM MySubQueryResult)
    AND my_date > (SELECT date FROM MySubQueryResult)
    Alternatively, you can also make use of joins to achieve the same.
    Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    Praveen Dsa | MCITP - Database Administrator 2008 |
    My Blog | My Page
    Dear Praveen Dsa
    Thanks for your reply, but order_no and date are paired and related, cannot separate.
    each order have its own date, so it is not working
    Best Regards
    swivan

Maybe you are looking for