SEELCT query

Hi all,
I have a table with the following fields: user_id, opt_col_id, width, ordering, udd_id
user_id is the PK. In this table either opt_col_id is null and udd_id has the value or vice-versa.
If opt_col_id is not null, it will be equal to: ref_opt_col.ID
If udd_id is not null, it will be equal to: customers_udd.udd_id
So I have the id (either opt_col_id or udd_id) in the user_opt_col table and I need to get the equvalent labels from either ref_opt_col or customers_udd tables.
If I run the following queries, I can get the data:
select u.opt_col_id, r.opt_col_label, u.ordering, u.width from ref_opt_col r, user_opt_col u, users users where r.id = u.opt_col_id and u.user_id = users.username and u.user_id = '?'
select u.udd_id, c.udd_label, u.ordering, u.width from user_opt_col u, users users, customers_udd c where u.user_id = users.username and u.udd_id = c.udd_id and u.user_id = '?'
Is there anyway that I can combine these two queries together and run only one SELECT query?
Any help is gretly appreciated.

Well, for an Oracle database, I would do it as:
SELECT NVL(u.opt_col_id, u.udd_id) as id,
       DECODE(u.opt_col_id, null, c.udd_label, r.opt_col_label) as label,
       u.ordering,
       u.width
FROM user_opt_col u,
     ref_opt_col r,
     customers_udd c,
     users users
WHERE u.user_id = users.username
  AND u.opt_col_id = r.id(+)
  AND u.udd_id = c.udd_id(+)
  AND u.user_id = ?DECODE is pretty Oracle-specific but many DBs have ways to do similar inline if-else tests on values. If your DB doesn't, you could return both ids and labels and sort out which one to use in the Java.
The (+) is an outer join; any self-respecting DB supports that, although possibly with different syntax.
Don't assume that doing it as one select is going to be faster (it likely will be on a sucky network or with a decent database product); the above query does quite a bit more work than the two simpler queries.
A whole different way of doing it would be with a stored procedure; a procedure might select the join of user_opt_col and users, inspect the id values, select whichever row it needs to, and return you the right results. Personally, I'd prefer the one query approach over an SP, in the abstract, but it's a judgment call and depends on your DB and your comfort with stored procedures.

Similar Messages

  • Seelct query time out for single region

    Hi ,
    I am currently facing a problem with a report .The problem is in a select query.The report runs successfully when it is run for only more than 1 state but when it is run for single state then it times out.The select query is as given below.
    SELECT avbeln eposnr bvbtyp aerdat akunnr ckunnr d~regio
               ewerks aernam dname1 afaksk b~cmgst
               INTO TABLE t_block
               FROM vbak AS a
               INNER JOIN vbuk AS b
               ON bvbeln = avbeln
               INNER JOIN vbpa AS c
               ON cvbeln = avbeln
               INNER JOIN kna1 AS d
              ON dkunnr = akunnr                             
               ON dkunnr = ckunnr                             
               INNER JOIN vbap AS e
               ON evbeln = avbeln
                   WHERE a~faksk IN faksk
                     AND a~vkorg = vkorg
                     AND a~vtweg IN vtweg
                     AND a~spart IN spart
                     AND a~vkbur IN vkbur
                     AND a~vkgrp IN vkgrp
                     AND a~kunnr IN kunnr
                     AND a~ernam IN ernam
                     AND a~erdat IN erdat
                     AND a~vbeln IN vbeln
                     AND a~vbtyp IN vbtyp
                     AND b~spstg IN ('A','B','C')
                     AND ( b~fsstk NE space
                          OR b~cmgst NE space )
                     AND b~abstk NE 'C'
                     AND c~kunnr IN s_kunwe
                     AND c~parvw = 'WE'
                     AND d~regio IN s_regio.
    Please let me know if you require any more information.
    s_regio is the select option for state.Also I feel that for KUNNR the On conditon might cause soem problem becasue it does not involve key fields.
    thanks,

    hi ds,
    separate the select in several selects. The inner join is not always the best solution.
    take
    data : ivbak type table of vbak,
       field symbols : <xvbak>
    select +++ into corresponding fields of table ivbuk
              from vbuk
              where
    select +++ into corresponding fields of table ivbak
             form vbak
             for all entries in ivbuk
             where vbeln eq ivbuk-vbeln ...
    select ...
    if you want to have one internal table then do it with a loop.
    loop at ivbak assigning <xvbak>
    read table ikna1 with key kunnr = <xvbak>-kunnr.
    loop at ivbap whee vbeln = <xvbak>-vbeln.
    itab..= vbak..
    ? move corresponding ?
    append itab.
    endloop.
    endloop.
    that will not cause a time-out.
    if you want a verry quick program - use tables without heading lines and field symbols with loops with assigning.
    It is more to write but the effect is verry good.
    Hans
    Hans

  • How to use decode for a not = expression ?

    Hi ,
    i want to use in my seelct query decode( val1 , IF not = 'abc' , sum(val1)
    how can i express it as a not equal or even a >= in a decode ?
    kindly advise
    tks & rdgs

    hi ,
    i have used a function to resolve my issue
    tks for all the info
    rdgsYou would be better doing it all in SQL for performance reasons so you do not context switch between PL/SQL and SQL all the time...
    Ok, without using CASE...
    SQL> create table a (stupid_number_in_varchar  VARCHAR2(10));
    Table created.
    SQL> insert into a
      2  select '3' as stupid_number_in_varchar from dual union all
      3  select 'X' from dual union all
      4  select '4' from dual union all
      5  select 'X' from dual union all
      6  select '5' from dual;
    5 rows created.
    -- Strip out non numeric values...
    SQL> ed
    Wrote file afiedt.buf
      1  select decode(stupid_number_in_varchar, 'X', null, stupid_number_in_varchar) as mynum
      2* from a
    SQL> /
    MYNUM
    3
    4
    5
    -- Only take numbers >= 4 ...
    SQL> ed
    Wrote file afiedt.buf
      1  select decode(sign(mynum-4), -1, null, mynum)
      2  from (
      3       select decode(stupid_number_in_varchar, 'X', null, stupid_number_in_varchar) as mynum
      4       from a
      5*      )
    SQL> /
    DECODE(SIG
    4
    5
    -- Sum the result...
    SQL> ed
    Wrote file afiedt.buf
      1  select sum(mynum) from
      2  (
      3    select decode(sign(mynum-4), -1, null, mynum) mynum
      4    from (
      5         select decode(stupid_number_in_varchar, 'X', null, stupid_number_in_varchar) as mynum
      6         from a
      7         )
      8*   )
    SQL> /
    SUM(MYNUM)
             9
    SQL>

  • How to make SELECT querry to work for CONVERSION EXIT

    Dear All,
    I want to select some data from from table J_1IEXCTAX , and to limit that retrieval I have WHERE clause for fields VALIDFROM and VALIDTO
    My select querry is like
    SELECT SINGLE RATE ECSRATE
                         FROM J_1IEXCTAX
                         INTO (J_1IEXCTAX-RATE,J_1IEXCTAX-ECSRATE)
                         WHERE J_1ICHID = J_1IMTCHID-J_1ICHID and
                              ( VALIDFROM LE     T_GRREC-BUDAT and                   
                                VALIDTO      GE     T_GRREC-BUDAT ).  
    But the field  VALIDFROM and VALIDTO have data (i.e. dates) in different format
    So my selection doesnt happen..
    these formats can be converted to desired format using  CONVERSION EXITs at their domain level...
    But that increases coding and worsens performance.....
    Could anybody give me some other solution?
    Thanks in advance................
    Code Formatted by: Alvaro Tejada Galindo on Jan 8, 2009 10:58 AM

    Hi,
    write T_GRREC-BUDAT to gv_date as <specify the format>
    now use gv_date in ur seelct query.
    Regards,
    Nagaraj

  • Select query that eliminate duplicates

    I am struck at the below scenario. need your help in modify my query based on the below sample data. My objective is to create a EVENT AND EVENT_LOW using the data available from TEM_GT and TXN table.
    TEM_GT (global temporary table)
    est_id primary key, trans_id, trp_id, amount
    1 111 2221 1.5
    2 111 3332 2.0
    3 112 4443 3.0
    TXN table
    trans_id, trans_type
    111 type1
    112 type1
    EVENT table
    event_id primary key, trans_id, trans_type, flag.
    1000 111 type1 N
    1001 112 type1 N
    EVENT_LOW table
    event_low_id primary key, event_id, est_id, amount.
    9991 1000 1 1.5
    9992 1000 1 2.0
    9993 1001 2 3.0
    insert into(event_low_id, event_id, est_id, amount)
    select event_low_id_s.nextval e.event_id, tg.est_id, tg.amount from
    from TEM_GT tg, EVENT e
    WHERE
    tg.trans_id = e.trans_id
    AND e.flag = 'N'
    Based on TEM_GT and TXN gt, populating data into EVENT table. Now when I try to populate data in the EVENT_LOW table, the above query returns 5 rows instead of 3 rows. This is due to trp_id in TEM_GT table. I do not want to add trp_id in EVENT table, and want to handle the duplicate elimination in the above select query.
    I wrote the below sql. It almost resolve my problem. But sometimes it returns different value for the amount column. I wanted my event_low result as below for the est_id 1.
    event_low_id primary key, event_id, est_id, amount.
    9991 1000 1 1.5
    9992 1000 1 2.0
    But sometime it returns as below
    event_low_id primary key, event_id, est_id, amount.
    9991 1000 1 1.5
    9992 1000 1 1.5
    or
    event_low_id primary key, event_id, est_id, amount.
    9991 1000 1 2.0
    9992 1000 1 2.0
    select *
    from (select x.*,
    row_number() over (partition by event_id order by event_id) rn
    from (seelct e.event_id, tg.est_id, tg.amount
    from TEM_GT tg, EVENT e
    WHERE
    tg.trans_id = e.trans_id
    AND e.flag = 'N'
    ) x
    where rn = 1
    I am using Oracle 11g. Any help. Thanks in advance.

    Hi Suresh,
    Please read SQL and PL/SQL FAQ
    Whenever you create a thread always post sample data as CREATE TABLE and INSERT statements.
    Additionally when you put some code or output please enclose it between two lines starting with {noformat}{noformat}
    i.e.:
    {noformat}{noformat}
    SELECT ...
    {noformat}{noformat}
    Regarding your problem you said:
    Based on TEM_GT and TXN gt, populating data into EVENT table. Now when I try to populate data in the EVENT_LOW table, the above query returns 5 rows instead of 3 rows.
    The above query cannot return 5 rows with the data you have posted. You have 3 rows in TEM_GT and 2 rows in EVENT table. The table are joined ontg.trans_id = e.trans_id AND e.flag = 'N'
    And the result of the query with your posted data is *3 rows*. So try to be clear.
    If your intention is to insert into EVENT_LOW only one row from TEM_GT for the same trans_id then you have to tell us which is the criteria to choose the row between the duplicates (the first by est_id order??).
    Also be careful to post valid statements. The statement below is not valid as it is missing the table name after INSERT INTO and there are 2 consecutive FROM keywords:insert into(event_low_id, event_id, est_id, amount)
    select event_low_id_s.nextval e.event_id, tg.est_id, tg.amount from
    from TEM_GT tg, EVENT e
    WHERE
    tg.trans_id = e.trans_id
    AND e.flag = 'N'
    I will make the assumption that you want to select the first row order by est_id during insertion. If this is not what you want, please change the analytic function:INSERT INTO event_low (event_low_id, event_id, est_id, amount)
    WITH got_data AS
    SELECT e.event_id, tg.est_id, tg.amount
    , ROW_NUMBER() OVER(PARTITION BY tg.trans_id ORDER BY tg.est_id) AS rn
    FROM tem_gt tg, event e
    WHERE tg.trans_id = e.trans_id
    AND e.flag = 'N'
    SELECT event_low_id_s.NEXTVAL
    , event_id, est_id, amount
    FROM got_data
    WHERE rn = 1;
    If this is not what you want please post CREATE TABLE and INSERT statement, and post your expected output (for insertion into EVENT_LOW table) for the data you have posted.
    Regards.
    Al                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Error while running a query-Input for variable 'Posting Period is invalid

    Hi All,
    NOTE: This error is only cropping up when I input 12 in the posting period variable selection. If I put in any other value from 1-11 I am not getting any errors. Any ideas why this might be happening?
    I am getting the following error when I try and run a query - "Input for variable 'Posting Period (Single entry, mandatory)' is invalid" - On further clicking on this error the message displayed is as follows -
    Diagnosis
    Variable Posting Period (Single Value Entry, Mandatory) is used as a lower limit (X) and an upper limit () in an interval selection. This limit has the value #.
    System Response
    Procedure
    Enter a different value for variable Posting Period (Single Value Entry, Mandatory). If the value of the other limit is determined by another variable, you can change its value also.
    Procedure for System Administration

    OK.
    Well, if the variable is not used in any interval selection, then I would say "something happened to it".
    I would make a copy of the query and run it to check if I get the same problem with period 12.
       -> If not, something is wrong in the original query (you can proceed as below, if changes to original are permitted).
    If so, then try removing the variable completely from the query and hardcode restriction to 12.
       -> If problem still persists, I would have to do some thinking.
    If problem is gone, then add the variable again. Check.
       -> If problem is back, then the variable "is sick". Only quick thing to do, is to build an identical variable and use that one.
    If problem also happens with the new variable, then it's time to share this experience with someone else and consider raising an OSS.
    Good luck!
    Jacob
    P.S: what fisc year variant are you using?
    Edited by: Jacob Jansen on Jan 25, 2010 8:36 PM

  • Logical database in adhoc query

    Hello All,
    Can anyone tell me what is the logical database in adhoc query?

    Hi
    When you create a query , you have to select an infoset. Infoset can be considered as a source from which data is populated in the Query Fields.
    Infosets are created from Transaction SQ02.
    There can be four methods through which an Infoset can become a source of data:
    1.  Table join ( By joining two or more tables from Data dictionary)
         example: Joining tables PA0001 and PA0006 on Pernr to get a one resultant dataset
    2. Direct read of Basis Table ( Like PA0001 as a source for data in Infoset )
    3. Logical Database ( A Pre-written Program by SAP that extract data from clusters, tables taking care of authorizations and validity periods)
    Example : Logical database PNP, PNPCE (Concurrent Employement),PCH ( LDB for Personnel Development Data)
    Custom Logical DBs can be created in T_Code SE-36.
    4. Data Retrieval by a Program ( Custom code written by ABAP developers which will collect and process data) . This program has a corresponding Structure in data dictionary and the fields of this structure will be used in query)
    Reward Points, if helpful.
    Regards
    Waseem Imran

  • Query help on Goods Receipt Query with AP Invoice

    Looking for a little help on a query.  I would like to list all the goods receipts for a given date range and then display the AP Invoice information (if its been copied to an AP Invoice).  I think my problem is in my where clause, I plagerized an SAP query to show GR and AP from a PO as a start.  SBO 2005 SP01.  Any help would be great appreciated.  Thanks
    SELECT distinct 'GR',
    D0.DocStatus,
    D0.DocNum ,
    D0.DocDate,
    D0.DocDueDate,
    D0.DocTotal,
    'AP',
    I0.DocStatus,
    I0.DocNum ,
    I0.DocDate,
    I0.DocDueDate,
    I0.DocTotal,
    I0.PaidToDate
    FROM
    ((OPDN  D0 inner Join PDN1 D1 on D0.DocEntry = D1.DocEntry)
    full outer join
    (OPCH I0 inner join PCH1 I1 on I0.DocEntry = I1.DocEntry)
    on (I1.BaseType=20 AND D1.DocEntry = I1.BaseEntry AND D1.LineNum=I1.BaseLine))
    WHERE
    (D1.BaseType=22 AND D1.DocDate>='[%0]' AND D1.DocDate<='[%1]')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry
    FROM PDN1 WHERE BaseType=22 AND DocDate>='[%0]' AND DocDate<='[%1]'))

    Hi Dalen ,
    I  believe it is because of the condition
    (D1.BaseType=22 AND D1.DocDate>='%0' AND D1.DocDate<='%1')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry FROM PDN1 WHERE PDN1.BaseType=22 AND DocDate>='%0' AND DocDate<='%1'))
    Try changing
    D1.BaseType=22 OR D1.DocDate>='%0' AND D1.DocDate<='%1
    PDN1.BaseType=22 OR DocDate>='%0' AND DocDate<='%1'))
    Lets see what would be the result . Lets have some fun with troubleshooting
    See what would be the difference in the result .
    Thank you
    Bishal

  • Can you check for data in one table or another but not both in one query?

    I have a situation where I need to link two tables together but the data may be in another (archive) table or different records are in both but I want the latest record from either table:
    ACCOUNT
    AccountID     Name   
    123               John Doe
    124               Jane Donaldson           
    125               Harold Douglas    
    MARKETER_ACCOUNT
    Key     AccountID     Marketer    StartDate     EndDate
    1001     123               10526          8/3/2008     9/27/2009
    1017     123               10987          9/28/2009     12/31/4712    (high date ~ which means currently with this marketer)
    1023     124               10541          12/03/2010     12/31/4712
    ARCHIVE
    Key     AccountID     Marketer    StartDate     EndDate
    1015     124               10526          8/3/2008     12/02/2010
    1033     125               10987         01/01/2011     01/31/2012  
    So my query needs to return the following:
    123     John Doe                        10526     8/3/2008     9/27/2009
    124     Jane Donaldson             10541     12/03/2010     12/31/4712     (this is the later of the two records for this account between archive and marketer_account tables)
    125     Harold Douglas               10987          01/01/2011     01/31/2012     (he is only in archive, so get this record)
    I'm unsure how to proceed in one query.  Note that I am reading in possibly multiple accounts at a time and returning a collection back to .net
    open CURSOR_ACCT
              select AccountID
              from
                     ACCOUNT A,
                     MARKETER_ACCOUNT M,
                     ARCHIVE R
               where A.AccountID = nvl((select max(M.EndDate) from Marketer_account M2
                                                    where M2.AccountID = A.AccountID),
                                                      (select max(R.EndDate) from Archive R2
                                                    where R2.AccountID = A.AccountID)
                   and upper(A.Name) like parameter || '%'
    <can you do a NVL like this?   probably not...   I want to be able to get the MAX record for that account off the MarketerACcount table OR the max record for that account off the Archive table, but not both>
    (parameter could be "DO", so I return all names starting with DO...)

    if I understand your description I would assume that for John Dow we would expect the second row from marketer_account  ("high date ~ which means currently with this marketer"). Here is a solution with analytic functions:
    drop table account;
    drop table marketer_account;
    drop table marketer_account_archive;
    create table account (
        id number
      , name varchar2(20)
    insert into account values (123, 'John Doe');
    insert into account values (124, 'Jane Donaldson');
    insert into account values (125, 'Harold Douglas');
    create table marketer_account (
        key number
      , AccountId number
      , MktKey number
      , FromDt date
      , ToDate date
    insert into marketer_account values (1001, 123, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('27.09.2009', 'dd.mm.yyyy'));
    insert into marketer_account values (1017, 123, 10987, to_date('28.09.2009', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
    insert into marketer_account values (1023, 124, 10541, to_date('03.12.2010', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
    create table marketer_account_archive (
        key number
      , AccountId number
      , MktKey number
      , FromDt date
      , ToDate date
    insert into marketer_account_archive values (1015, 124, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('02.12.2010', 'dd.mm.yyyy'));
    insert into marketer_account_archive values (1033, 125, 10987, to_date('01.01.2011', 'dd.mm.yyyy'), to_date('31.01.2012', 'dd.mm.yyyy'));
    select key, AccountId, MktKey, FromDt, ToDate
         , max(FromDt) over(partition by AccountId) max_FromDt
      from marketer_account
    union all
    select key, AccountId, MktKey, FromDt, ToDate
         , max(FromDt) over(partition by AccountId) max_FromDt
      from marketer_account_archive;
    with
    basedata as (
    select key, AccountId, MktKey, FromDt, ToDate
      from marketer_account
    union all
    select key, AccountId, MktKey, FromDt, ToDate
      from marketer_account_archive
    basedata_with_max_intervals as (
    select key, AccountId, MktKey, FromDt, ToDate
         , row_number() over(partition by AccountId order by FromDt desc) FromDt_Rank
      from basedata
    filtered_basedata as (
    select key, AccountId, MktKey, FromDt, ToDate from basedata_with_max_intervals where FromDt_Rank = 1
    select a.id
         , a.name
         , b.MktKey
         , b.FromDt
         , b.ToDate
      from account a
      join filtered_basedata b
        on (a.id = b.AccountId)
    ID NAME                     MKTKEY FROMDT     TODATE
    123 John Doe                  10987 28.09.2009 31.12.4712
    124 Jane Donaldson            10541 03.12.2010 31.12.4712
    125 Harold Douglas            10987 01.01.2011 31.01.2012
    If your tables are big it could be necessary to do the filtering (according to your condition) in an early step (the first CTE).
    Regards
    Martin

  • Query help : Query to get values SYSDATE-1 18:00 hrs to SYSDATE 08:00 hrs

    Hi Team
    I want the SQl query to get the data for the following comparison : -
    Order Created is a Date Column , and i want to find out all the values from (SYSDATE-1) 18:00 hours to SYSDATE 08:00 hours
    i.e.
    (SYSDATE-1) 18:00:00 < Order.Created < SYSDATE 08:00:00.
    Regards

    Hi, Rohit,
    942281 wrote:
    If i want the data in the below way i.e.
    from (SYSDATE-1) 18:00 hours to SYSDATE 17:59 hours ---> (SYSDATE-1) 18:00:00 < Order.Created < SYSDATE 07:59:00.If you want to include rows from exactly 18:00:00 yesterday (but no earlier), and exclude rows from exatly 08:00:00 today (or later), then use:
    WHERE   ord_dtl.submit_dt  >= TRUNC (SYSDATE) - (6 / 24)
    AND     ord_dtl.submit_dt  <  TRUNC (SYSDATE) + (8 / 24)
    So can i use the below format : -
    ord_dtl.submit_dt BETWEEN trunc(sysdate)-(6/24) and trunc(sysdate)+(7.59/24) . Please suggest . .59 hours is .59 * 60 * 60 = 2124 seconds (or .59 * 60 = 35.4 minutes), so the last time included in the range above is 07:35:24, not 07:59:59.
    If you really, really want to use BETWEEN (which includes both end points), then you could do it with date arithmentic:
    WHERE   ord_dtl.submit_dt  BETWEEN  TRUNC (SYSDATE) - (6 / 24)
                      AND         TRUNC (SYSDATE) + (8 / 24)
                                               - (1 / (24 * 60 * 60))but it would be simpler and less error prone to use INTERVALs, as Karthick suggested earlier:
    WHERE   ord_dtl.submit_dt  BETWEEN  TRUNC (SYSDATE) - INTERVAL '6' HOUR
                      AND         TRUNC (SYSDATE) + INTERVAL '8' HOUR
                                               - INTERVAL '1' SECONDEdited by: Frank Kulash on Apr 17, 2013 9:36 AM
    Edited by: Frank Kulash on Apr 17, 2013 11:56 AM
    Changed "- (8 /24)" to "+ (8 /24)" in first code fragment (after Blushadown, below)

  • Query help, subtract two query parts

    Hi,
    I am beginner of PL/SQL and have a problem I couldn’t solve:
    Table (op_list):
    Item     -     Amount -     Status
    Item1     -     10     -     in
    Item2     -     12     -     in
    Item3     -     7     -     in
    Item1     -     2     -     out
    Item2     -     3     -     out
    Item1     -     1     -     dmg
    Item3     -     3     -     out
    Item1     -     2     -     out
    Item2     -     5     -     out
    Item2     -     2     -     in
    Item3     -     1     -     exp
    Would like to get result of query (subtract amount of 'out/dmg/exp' from 'in' ):
    Item - Amount left
    Item1     -     5
    Item2     -     6
    Item3 -     3
    I wrote code that returns sum of all incoming items and sum all out/dmg/exp items, but couldn’t solve how to subtract one part of querry from another. Or maybe there is a better way. Also worried what happens if there is no 'out/dmg/exp' only 'in'
    select item.name, sum(op_list.item_amount)
    from op_list
    inner join item
    on op_list.item = item.item_id
    where op_list.status = 'in'
    group by item.name
    union
    select item.name, sum(op_list.item_amount)
    from op_list
    inner join item
    on op_list.item = item.item_id
    where op_list.status = 'out'
    or op_list.status = 'dmg'
    or op_list.status = 'exp'
    group by item.name
    Return:
    Item1     -     10      [10 in]
    Item1     -     5     [2+1+2]
    Item2     -     14     [12+2]
    Item3     -     7
    Item3     -     4     [3+1]
    Thanks in advance

    Hi,
    We can also use simple inline views to get what we need.
    select a.item,a.amount-b.amount Balance from
    (select item,sum(amount) Amount from op_list
    where status = 'in'
    group by item) a,
    (select item,sum(amount) Amount from op_list
    where status in ('out','dmg','exp')
    group by item) b
    where
    a.item=b.item
    order by item;
    ITEM       BALANCE
    Item1                      5
    Item2                      6
    Item3                      3Regards,
    Prazy

  • Query help: query to return column that represents multiple rows

    I have a table with a name and location column. The same name can occur multiple times with any arbitrary location, i.e. duplicates are allowed.
    I need a query to find all names that occur in both of two separate locations.
    For example,
    bob usa
    bob mexico
    dot mexico
    dot europe
    hal usa
    hal europe
    sal usa
    sal mexico
    The query in question, if given the locations usa and mexico, would return bob and sal.
    Thanks for any help or advice,
    -=beeky

    How about this?
    SELECT  NAME
    FROM    <LOCATIONS_TABLE>
    WHERE   LOCATION IN ('usa','mexico')
    GROUP BY NAME
    HAVING COUNT(DISTINCT LOCATION) >= 2Results:
    SQL> WITH person_locations AS
      2  (
      3          SELECT 'bob' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      4          SELECT 'bob' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      5          SELECT 'dot' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      6          SELECT 'dot' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      7          SELECT 'hal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      8          SELECT 'hal' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      9          SELECT 'sal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
    10          SELECT 'sal' AS NAME, 'Mexico' AS LOCATION FROM DUAL
    11  )
    12  SELECT  NAME
    13  FROM    person_locations
    14  WHERE   LOCATION IN ('USA','Mexico')
    15  GROUP BY NAME
    16  HAVING COUNT(DISTINCT LOCATION) >= 2
    17  /
    NAM
    bob
    salHTH!
    Edited by: Centinul on Oct 15, 2009 2:25 PM
    Added sample results.

  • QUERY HELP!!! trying to create a query

    i'm creating a summary report
    i have a table with sale dates
    for example i have a table tab_1 and column saleDate as
    saleDat
    1923
    1936
    1945
    2003
    2005
    saleDate contains years and there are some missing years where no sale
    was made
    My report has to display years starting from earliest year
    so i have to create a query that starts with 1923
    but the problem is that I have to have years that are not in table.
    for example i have to display years 1924 which is not in table
    so the part of report has to look like
    1923 blah blah summary.........
    1924 "
    1925
    1926
    2005
    2006
    upto current year (2006 may not be in the table, but i have to display)
    i just need to know the query that can query all the years starting from
    the ealiest saleDate to current year
    thanks in advance

    Please write the query in the following form:
    SELECT a.year, --- place other columns from your table.
    FROM (SELECT (:start_num + rownum) year
    FROM all_tab_columns
    WHERE :start_num + rownum <= :end_num) a,
    tab_1 b
    WHERE a.year = b.saleDat(+);
    Note:
    1) if your start year and end year are 1923 and 2006. Then input as below:
    :start_num = 1922
    :end_num = 2006
    2) Since for some of the years (1924 etc) may not be there in your so you may need to use NVL to print proper indicators.
    3) If you have more than one record in tab_1 for a particular year then group them based year and then use it.
    Hope this helps.
    - Saumen.

  • IF statement in Query

    Hi
    I have a query / recordset that  would be looking at 12000 rows in a database and 10 different variables and potential filters chosen by end users.
    Should I put 10 wild card / url Where statements in my recordset query or should I put IF statements in my query.
    ie.
    If URL colname then ",and BetType= "xzz"" .
    Is that the most efficient way to run my queries.
    I will be running about 10 recordsets on my page all looking at these url variables so it will be a busy page.
    If that is the answer can someone please tell me how to insert the if statement - i've tried allsorts but it wont work.
    $colname_Recordset4 = "%";
    if (isset($_GET['colname'])) {
      $colname_Recordset4 = $_GET['colname'];
    mysql_select_db($database_racing_analysis, $racing_analysis);
    $query_Recordset4 = sprintf("SELECT BetType, sum(if(season='2006-2007', Bet, 0)) AS '2006-2007',  sum(if(season='2007-2008', Bet, 0)) AS '2007-2008',  sum(if(season='2008-2009', Bet, 0)) AS '2008-2009' FROM dataextract WHERE BetType Like %s and TrackID = 1 and Distance = 1000 and Class = 1 GROUP BY BetType", GetSQLValueString($colname_Recordset4, "text"));
    $Recordset4 = mysql_query($query_Recordset4, $racing_analysis) or die(mysql_error());
    $row_Recordset4 = mysql_fetch_assoc($Recordset4);
    $totalRows_Recordset4 = mysql_num_rows($Recordset4);
    hope someone can help.
    Simon

    That part of the query cross tabs my data into three columns - not intended to confuse the issue. I'd have the same problem with a basic query.
    So Here is a very basic version:
    I want an IF statement to go around: "WHERE Distance = 1000" and "AND Class = 1"
    That I believe will reduce the effort on the MYSQL Server as it wouldn't be running a bunch of wild card queries and would only run if there is a URL paramter delivered.??
    I just don't get how to put the IF statements in PHP.
    thanks
    $maxRows_Recordset3 = 5;
    $pageNum_Recordset3 = 0;
    if (isset($_GET['pageNum_Recordset3'])) {
      $pageNum_Recordset3 = $_GET['pageNum_Recordset3'];
    $startRow_Recordset3 = $pageNum_Recordset3 * $maxRows_Recordset3;
    mysql_select_db($database_racing_analysis, $racing_analysis);
    $query_Recordset3 = "SELECT * FROM dataextract WHERE Distance = 1000 AND Class = 1";
    $query_limit_Recordset3 = sprintf("%s LIMIT %d, %d", $query_Recordset3, $startRow_Recordset3, $maxRows_Recordset3);
    $Recordset3 = mysql_query($query_limit_Recordset3, $racing_analysis) or die(mysql_error());
    $row_Recordset3 = mysql_fetch_assoc($Recordset3);
    if (isset($_GET['totalRows_Recordset3'])) {
      $totalRows_Recordset3 = $_GET['totalRows_Recordset3'];
    } else {
      $all_Recordset3 = mysql_query($query_Recordset3);
      $totalRows_Recordset3 = mysql_num_rows($all_Recordset3);
    $totalPages_Recordset3 = ceil($totalRows_Recordset3/$maxRows_Recordset3)-1;

  • IF and ABS condition statement in BEX query designer

    Hi,
    I would like to ask the best way for me to produce an acceptable result from Excel IF and ABS Condition statement.
    The condition statement that I have on my Excel file is
    =IF((A2-B2)>0,ABS(A2-B2),0)
    I'm trying multiple times to reproduce this in BEX Query designer, unfortunately I'm getting a bad result or unacceptable formula.
    Anyone who could help me with my issue?
    Thanks,
    Arnold

    Hi Arnold,
    Thank you,
    Nanda

Maybe you are looking for

  • I deleted some videos from camera roll but they still appear in the videos folder

    I removed some videos from my 4s to my computer but they still appear in a file called videos on my phone.  The file Videos doesn't show up on my computer when I plug my phone in to the USB.  How can I see this file on my computer when my phone is pl

  • How do you Redistribution EIGRP into OSPF and maintain a distance of 250 for a static route?

    Ok, I have scoured the forums long enough and have to post. The design is below. I moved a firewall to our new data center, which required adding some static routes for VPN connections and broadband backups. To minimize the amount of static routes I

  • Issue with inbound EDI idocs

    Hi we are receiving inbound EDI idocs throgh third party.  Third party received EDI file having 5000 transactions . It was transalated same number of idocs text document and posted in SAP.  But after 4 hours same file processed in SAP. Third party sa

  • Transitions  (Random) in Keynote.

    Why in the new Key Note that we still do not have "Random" Transitions. I find it very frustrating making a slide selection, and having to select each slide to get a different Transition. Then If I want to change the timing on all the Slides it chang

  • Having Issues updating to iOS 5...help??

    Everytime I've tried to finish the update for iOS 5 on my iPod this message keeps showing up.Anyone have any ideas of what I should do???