Unpivot query help

Hi ALL
I have the following sample data:
AMENDMENT_DATES_ID     AMENDMENT_ID     ENTRY_DATE     AMENDMENT_DATE_CODE
29710     1     12/20/2007     15
31852     2     1/17/2006     29
31860     3     2/9/2006     29
31868     4     9/13/2007     29
31876     6     3/28/2006     29
29994     88     11/21/2007     6
31890     9     8/23/2006     29
I tried to create seperate fields based on the "AMENDMENT_DATE_CODE" using CASE AND DECODE but was not successful. I need the values of the field "AMENDMENT_DATE_CODE" as seperate fields, like :
AMENDMENT_DATES_ID AMENDMENT_ID ENTRY_DATE 15 29 6
Please need help.
Thanks

Hi,
Unpivot means display multiple columns from one row as if they were one column on multiple rows.
It looks like you want to do the opposite: display the same column from 3 rows as 3 columns on 1 row. That's called Pivot .
This thread shows what you need:
Help for a query to add columns
That example used the aggregate COUNT; you'll probably want MIN or MAX instead. If the combination (AMENDMENT_DATES_ID, AMENDMENT_ID, ENTRY_DATE, AMENDMENT_DATE_CODE) is unique, it won't matter whethere you use MIN or MAX; when there's no more than 1 item, the largest one is the same as the smallest.
As you can see from that thread, there is a different (better) way of doing pivots starting in Oracle 11. What version are you using?
If you'd like help, post a little sample data (CREATE TABLE and INSERT statements), the results you want from that data, and your best attempt at a query.

Similar Messages

  • Oracle 11g unpivot query help

    Hello,
    I have a single row of data showing school term start and end dates in 2011/12. I need to convert this single row of data (containing 16 columns) into 5 rows comprised of just 4 columns (year, term, term_start, term_end).
    Is it possible to use just Oracle 11g's unpivot function_ to convert the following 16 columns of data:
    select * from
    (select 2012 as terms_year,
    1 as T1,'05-SEP-2011' as T1_SD, '21-OCT-2011' as T1_ED,
    2 as T2,'31-OCT-2011' as T2_SD, '16-DEC-2011' as T2_ED,
    3 as T3,'03-JAN-2012' as T3_SD, '10-FEB-2012' as T3_ED,
    4 as T4,'20-FEB-2012' as T4_SD, '30-APR-2012' as T4_ED,
    5 as T5,'16-APR-2012' as T5_SD, '01-JUN-2012' as T5_ED
    from dual) mytable
    aka
    TERMS_YEAR             T1                     T1_SD       T1_ED       T2                     T2_SD       T2_ED       T3                     T3_SD       T3_ED       T4                     T4_SD       T4_ED       T5                     T5_SD       T5_ED      
    2012                   1                      05-SEP-2011 21-OCT-2011 2                      31-OCT-2011 16-DEC-2011 3                      03-JAN-2012 10-FEB-2012 4                      20-FEB-2012 30-APR-2012 5                      16-APR-2012 01-JUN-2012 into the following 4 columns of data (year, term, term_start, term_end):
    select terms_year, term, t1_sd as term_start, t1_ed as term_end from
    (select 2012 as terms_year, 1 as term, '05-SEP-2011' as T1_SD, '21-OCT-2011' as T1_ED from dual union all
    select 2012 as terms_year, 2 as term, '31-OCT-2011' as T2_SD, '16-DEC-2011' as T2_ED from dual union all
    select 2012 as terms_year, 3 as term, '03-JAN-2012' as T3_SD, '10-FEB-2012' as T3_ED from dual union all
    select 2012 as terms_year, 4 as term, '20-FEB-2012' as T4_SD, '30-APR-2012' as T4_ED from dual union all
    select 2012 as terms_year, 5 as term, '16-APR-2012' as T5_SD, '01-JUN-2012' as T5_ED from dual) mytable
    aka
    TERMS_YEAR             TERM                   TERM_START  TERM_END   
    2012                   1                      05-SEP-2011 21-OCT-2011
    2012                   2                      31-OCT-2011 16-DEC-2011
    2012                   3                      03-JAN-2012 10-FEB-2012
    2012                   4                      20-FEB-2012 30-APR-2012
    2012                   5                      16-APR-2012 01-JUN-2012 Much obliged if anyone can teach me how - I can't get my head around the pivot/unpivot syntax! E.g.
    Select *
    From mytable
    UNPIVOT (
    unpivot_clause
    unpivot_for_clause
    unpivot_in_clause)
    Thanks,
    TP.

    Hi,
    Using the SELECT ... PIVOT feature:
    SELECT       terms_year
    ,       term
    ,       term_start
    ,       term_end
    FROM       mytable
    UNPIVOT       (  ( term
              , term_start
              , term_end
              )     FOR num_col
                 IN ( (t1, t1_sd, t1_ed)     AS 1
                 , (t2, t2_sd, t2_ed)     AS 2
                 , (t3, t3_sd, t3_ed)     AS 3
                 , (t4, t4_sd, t4_ed)     AS 4
                 , (t5, t5_sd, t5_ed)     AS 5
    ORDER BY  terms_year     -- If needed
    ,            num_col
    ;The basic syntax for UNPIVOTing to 1 column (plus a label column) is
    UNPIVOT (    outcol
         FOR  label     IN ( incol_1  AS label_val_1
                           , incol_2  AS label_val_2
                      , incol_n  AS label_val_n
         )where
    outcol       is the pivoted output column, containing values from the original table,
    label       is a label column, which will contain values hard-coded in the query,
    incol_1, incol_2, ..., incol_n       are the columns from the origianl table to be unpivoted
    label_val_1, label_val_2, ..., label_val_n       are the hard-coded values that will go in the label column.
    The syntax for pivoting to m columns (m > 1) is like that for pivoting 1 column, but
    instead of outcol, you give a comma-delimited list of m outcols, enclosed in parentheses, and
    instead of incol_1, incol_2, ... incol_n, you give a comma-delimited list of m columns, enclosed in parentheses.
    By the way, storing dates in VARCHAR2 columns is not a very good idea. Use DATE columns instead.
    Edited by: Frank Kulash on Jul 16, 2012 6:11 PM

  • Query Help-2

    Query Help:
    http://forum.java.sun.com/thread.jsp?forum=45&thread=471180&tstart=15&trange=15
    It seems I have confused enough people with my improper presentation of query. Sorry guys. I will restate my question with different table names.
    The above was my previous posting, which was not clear..so Iam restating my problem as follows....
    I have the following tables
    Customer(custID, Name, Address)
    Order(custID, OrderID, orderDate)
    CreditCard(custID, creditCard#, creditCardType)
    Now if I have 3 records in Order with custID 100 and 2 records in CreditCard as
    Order:
    100,A001,11/22/03
    100,A002,11/24/03
    100,A003,12/02/03
    CreditCard:
    100,42323232..., VISA
    100,5234234...., MASTER
    Now how can I get
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    data in minimum no. of records....
    I think I have made my query clear..
    now please help me guys...
    thanks so much for your help.

    You are right.
    But frankly the actual tables on my database are not customer,orders and creditcards..but I just tried to reproduce the problem with these tables, please ignore that user needs a refund etc situtaion. If the tables were actually order,creditcards etc..it would have been a problem to be considered.
    Can you please help me with the query
    if I have m rows in Order and n rows in CreditCard. I will get m*n records, I looking for max(m,n).
    With the following fields in my query result,
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    from Customer, Order, CreditCard tables
    Thanks so much for your htlp

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

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

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

  • Unpivot query error

    Hi,
    I am running an oracle 11gR2 Database.
    I have a table of the structure..
    CREATE TABLE "RP_RESOLUTION_MASTER"
    ( "RM_ID" NUMBER,
    "SR_ID" NUMBER,
    "REQUEST_STATUS" VARCHAR2(200 BYTE),
    "COMMENTS" VARCHAR2(4000 BYTE),
    "UPDATED_ON" DATE,
    "UPDATED_BY" VARCHAR2(500 BYTE),
    "INTERNAL_COMMUNICATION" VARCHAR2(1 BYTE) DEFAULT 'N'
    I am running an unpivot query on this.
    SELECT *
    From Rp_Resolution_Master
    Unpivot INCLUDE NULLS (
    value For measures In ( rm_id, request_status, Comments
    , updated_by, internal_communication)
    where sr_id = 1004707
    And Updated_On = ( Select Max(Updated_On)
    From Rp_Resolution_Master
    Where Sr_Id = 1004707);
    But I get an error
    ORA-01790: expression must have same datatype as corresponding expression
    01790. 00000 - "expression must have same datatype as corresponding expression" *Cause:
    *Action: Error at Line: 3 Column: 51
    What is it that I am doing wrong here?

    The columns you're trying to unpivot are not of the same datatype, hence the error.
    You have to convert them to a common datatype first :
    SQL> select empno, measure, val
      2  from scott.emp
      3  unpivot ( val for measure in (ename, sal) )
      4  where mgr = 7698
      5  ;
    unpivot ( val for measure in (ename, sal) )
    ERROR at line 3:
    ORA-01790: expression must have same datatype as corresponding expression
    SQL> with emp2 as (
      2    select empno
      3         , mgr
      4         , ename
      5         , to_char(sal) as sal
      6    from scott.emp
      7  )
      8  select empno, measure, val
      9  from emp2
    10  unpivot ( val for measure in (ename, sal) )
    11  where mgr = 7698
    12  ;
         EMPNO MEASU VAL
          7499 ENAME ALLEN
          7499 SAL   1600
          7521 ENAME WARD
          7521 SAL   1250
          7654 ENAME MARTIN
          7654 SAL   1250
          7844 ENAME TURNER
          7844 SAL   1500
          7900 ENAME JAMES
          7900 SAL   950
    10 rows selected.

  • Need a query help

    hii
    i need a query help
    i have two tables
    the 1st table will look like this
    associate id weekid no.of. hours
    4000 810 40
    4000 820 30
    4000 830 60
    4000 840 70
    2nd table will look like this
    associate id weekid no.of.hours
    4000 810 40
    4000 820 70
    4000 830 130
    4000 840 200
    so when i subtract the last two records frm each other in the second table the value should be equal to the no.of.hours in the first table.. for example
    the query shud consider the last record and one before the last record and the difference between two records shud be equal to the value in the 1st table
    for example
    consider week id 830 and 840
    in second table 830=130
    840=200
    when u subtraced both values the difference shud be equal to value in the 1st table for tht week id
    1 ---->>>> 840 - 830
    =200 - 130
    =70
    in first table 840 has 70 hrs
    like this it shud check with all records and it shud return only the records which are not equal
    regards
    srikanth

    This..?
    sql>select * from t1;
    A_ID W_ID HRS
    4000  810  40 
    4000  820  30 
    4000  830  60 
    4000  840  70 
    4000  850  80 
    sql>select * from t2;
    A_ID W_ID HRS 
    4000  810  40 
    4000  820  70 
    4000  830  130 
    4000  840  200 
    4000  850  260 
    sql>
    select a_id,w_id,hrs,sum_hrs
    from(
    select t1.a_id a_id,t1.w_id w_id,t1.hrs hrs,t2.hrs sum_hrs,
           t2.hrs - nvl(lag(t2.hrs)  over(order by t1.w_id),0) diff
    from t1,t2
    where t1.w_id = t2.w_id)
    where diff != hrs;
    A_ID W_ID HRS SUM_HRS 
    4000  850  80  260                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Pivot query help

    Hi All,
    I have a table as
    Create table carClass (
    carClassID  number,
    carID        number,
    baseYear   number, --Base Year
    Year_0      number, --Total for Base year
    Year_1      number, --Total for Base year minus 1
    Year_2      number ) --Total for Base year minus 2
    insert into carClass (carClassID, carID, baseYear, Year_0, Year_1, Year_2)     values ( 1,1,2010,10,5,3);
    insert into carClass (carClassID, carID, baseYear, Year_0, Year_1, Year_2)     values ( 1,1,2013,12,3,2);
    insert into carClass (carClassID, carID, baseYear, Year_0, Year_1, Year_2)     values ( 1,2,2019,20,10,5);
    insert into carClass (carClassID, carID, baseYear, Year_0, Year_1, Year_2)     values ( 2,1,2014,25,12,6);
    insert into carClass (carClassID, carID, baseYear, Year_0, Year_1, Year_2)     values ( 2,2,2011,8,4,2);
    insert into carClass (carClassID, carID, baseYear, Year_0, Year_1, Year_2)     values ( 2,3,2012,9,6,3);
    insert into carClass (carClassID, carID, baseYear, Year_0, Year_1, Year_2)     values ( 3,1,2015,14,7,4);
    insert into carClass (carClassID, carID, baseYear, Year_0, Year_1, Year_2)     values ( 3,2,2017,12,9,8);
    insert into carClass (carClassID, carID, baseYear, Year_0, Year_1, Year_2)     values ( 3,2,2015,16,14,2);If Base year column "baseYear" is 2014, Year_0 total is for year 2014, Year_1 total is for year 2013 and Year_2 total is for year 2012.
    I would like to SUM the total for all carClass except for carClassID = 3 that I want the totals base on CarID
    The result is:
    Class CarID     2008     2009     2010     2011     2012     2013     2014     2015     2016     2017     2018     2019
    1          3     5     12     3     12     0     0     0     0     5     10     20
    2          0     2     7     14     9     0     0     0     0     0     0     0
    3     1     0     0     0     0     0     4     7     14     0     0     0     0
    3     2     0     0     0     0     0     2     14     24     9     12     0     0Any help will be appreciate.
    Thanks!

    Hi,
    Whenever you have a question, please say which version of Oracle you're using. This is especially important with pivot problems, because the SELECT ... PIVOT and SELECT ... UNPIVOT features, both of which could be used in this problem, were only introduced in Oracle 11.1.
    Here's one way:
    WITH   cntr           AS
         SELECT     LEVEL - 1     AS n
         FROM     dual
         CONNECT BY     LEVEL     <= 3
    ,     unpivoted_data     AS
         SELECT     cc.carClassID
         ,     CASE
                  WHEN  cc.carClassID = 3
                  THEN  cc.carID
              END               AS carID3
         ,     cc.baseYear - cn.n     AS yr
         ,     CASE  cn.n
                  WHEN  0  THEN  cc.year_0 
                  WHEN  1  THEN  cc.year_1 
                  WHEN  2  THEN  cc.year_2 
              END               AS amt
         FROM          carClass  cc
         CROSS JOIN     cntr       cn
    SELECT       carClassID, carID3
    ,       SUM (CASE WHEN yr = 2008 THEN amt ELSE 0 END)     AS yr2008
    ,       SUM (CASE WHEN yr = 2009 THEN amt ELSE 0 END)     AS yr2009
    ,       SUM (CASE WHEN yr = 2010 THEN amt ELSE 0 END)     AS yr2010
    ,       SUM (CASE WHEN yr = 2019 THEN amt ELSE 0 END)     AS yr2019
    FROM       unpivoted_data
    GROUP BY  carClassID, carID3
    ORDER BY  carClassID
    ;The results I get:
    CARCLASSID     CARID3     YR2008     YR2009     YR2010     YR2019
             1                     3          5         10         20
             2                     0          2          7          0
             3          1          0          0          0          0
             3          2          0          0          0          0aren't exqactly what you posted. That could be due to typos in your message. If not, point out where the results are wrong, and explain, step by step, how you figure the correct results in those places.
    Since I don't know which version of Oracle you're running, I only used features that are available in Oracle 9.1. Of course, this works in all later versions as well.
    In SQL, the number of columns and their aliases (such as yr2008) has to be hard-coded into any query.
    If you want the query itself to determine how many different years there are, and what those years are, then see {message:id=3527823}

  • Complex UNPIVOT query

    I'm working with a table that has a one column per month, the data in the month columns is a code. I need to return one line for every set of codes stating the start and end date that those codes were active. If the code = 0 then it's inactive, otherwise the code corresponds with the date range.
    Example of data that was easy to code:
    IDNum | YearNm   |   month_01 | month_02 | month_03 | month_04 | month_05 ...
    123       2011        10          10          10         0          0     
    456       2011        0           20          20         10         0
    Output:
    IDNum  | Code |   StartDT  |   EndDT
    123       10    01-JAN-2011   31-MAR-2011
    456       20    01-FEB-2011   31-MAR-2011
    456       10    01-APR-2011   30-APR-2011this was done with a query like:
    SELECT IDNum, Code, TO_DATE('01/'||MIN(months)||YearNM) as StartDT,
    LAST_DAY(TO_DATE('01/'||MAX(months)||YearNM) as EndDT
    FROM monthly_table
    UNPIVOT (Code FOR months in (month_01 as '01', month_02 as '02', month_03 as '03', month_04 as '04', month_05 as '05' ...)
    GROUP BY  IDNum, Code, YearNMAll is well until we have data like this:
    IDNum | YearNm |   month_01 | month_02 | month_03 | month_04 | month_05 ...
    789      2011        10          10         0          10          10      We are expecting to have results like:
    IDNum  | Code |   StartDT      |   EndDT
    789         10      01-JAN-2011   28-FEB-2011
    789         10      01-APR-2011   31-MAY-2011Instead we get (obviously because of the MAX(months)):
    IDNum  | Code |   StartDT      |   EndDT
    789         10      01-JAN-2011   31-MAY-2011I'm thinking that the UNPIVOT isn't the right way to approach this, but I can't work out how to pull out these sets of monthly data. Any help on how I should approach this would be very much appreciated.
    Edited by: 947130 on Jul 17, 2012 3:41 PM

    Use start of group method:
    with t1 as (
                select  idnum,
                        yearnum,
                        month,
                        case month
                          when 1  then month_01
                          when 2  then month_02
                          when 3  then month_03
                          when 4  then month_04
                          when 5  then month_05
    /* commented out since you provided 5 month data only
                          when 6  then month_06
                          when 7  then month_07
                          when 8  then month_08
                          when 9  then month_09
                          when 10 then month_10
                          when 11 then month_11
                          else month_12
                        end code
                  from  tbl,
                         select  level month
                           from  dual
                           connect by level <= 5 -- should be 12, I use 5 since you provided 5 month data only
         t2 as (
                select  idnum,
                        yearnum,
                        month,
                        code,
                        case lag(code) over(partition by idnum,yearnum order by month)
                          when code then 0
                          else 1
                        end start_of_group
                  from  t1
         t3 as (
                select  idnum,
                        yearnum,
                        month,
                        code,
                        sum(start_of_group) over(partition by idnum,yearnum order by month) grp
                  from  t2
    select  idnum,
            code,
            to_date(yearnum || '/' || min(month) || '/01','yyyy/mm/dd') startdate,
            last_day(to_date(yearnum || '/' || max(month) || '/01','yyyy/mm/dd')) enddate
      from  t3
      group by idnum,
               yearnum,
               grp,
               code
      order by idnum,
               yearnum,
               grp,
               code
         IDNUM       CODE STARTDATE ENDDATE
           123         10 01-JAN-11 31-MAR-11
           123          0 01-APR-11 31-MAY-11
           456          0 01-JAN-11 31-JAN-11
           456         20 01-FEB-11 31-MAR-11
           456         10 01-APR-11 30-APR-11
           456          0 01-MAY-11 31-MAY-11
           789         10 01-JAN-11 28-FEB-11
           789          0 01-MAR-11 31-MAR-11
           789         10 01-APR-11 31-MAY-11
    9 rows selected.
    SQL> SY.

  • 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

  • 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.

  • Pulling open invoices, and paid invoices with details (Query Help).

    Hello All,
    I am sure I messed something up in my joins. I am looking to pull a report of all invoices OINV for a month, then list details of any payment (if it is paid) next to it from RCT2. It is giving me a list of all of the paid invoices, but even though I have a LEFT JOIN it is not listing any of the invoices without payments.
    This is where I am now from the report wizard in Crystal.
    SELECT "OINV"."DocNum", "OINV"."SlpCode", "OINV"."CardCode", "OINV"."DocTotal", "OINV"."U_Commission", "OSLP"."SlpName", "RCT2"."DcntSum", "ORCT"."TaxDate", "OINV"."DocEntry", "OINV"."TotalExpns", "OINV"."CANCELED", "ORCT"."Canceled", "ORCT"."DocNum", "RCT2"."InvType"
    FROM   ("DBName"."dbo"."OINV" "OINV" LEFT OUTER JOIN "DBName"."dbo"."OSLP" "OSLP" ON "OINV"."SlpCode"="OSLP"."SlpCode")
    INNER JOIN ("DBName"."dbo"."ORCT" "ORCT" INNER JOIN "DBName"."dbo"."RCT2" "RCT2" ON "ORCT"."DocNum"="RCT2"."DocNum")
    ON "OINV"."DocEntry"="RCT2"."DocEntry"
    WHERE  "OINV"."CANCELED"='N' AND "ORCT"."Canceled"='N' AND "RCT2"."InvType"<=N'14'
    ORDER BY "OINV"."SlpCode", "ORCT"."DocNum", "ORCT"."TaxDate"
    Thank you in advance for any help you can give me.

    Hello Kiran,
    I thought about that, but my purposes for running the report is to determine commission based on the date that the invoice was paid, I need the TaxDate in ORCT as it relates to the payment in RCT2.
    Removing the ORCT.cancelled condition and the RCT2.invtype conditions now pulls all of the invoices, paid and unpaid. I know now I cant have them in my query, when the record does not exist in ORCT it doesnt have a value for cancelled, and when there is no record in RCT2 there is no invtype, and is filtered.
    Maybe I can say where ORCT.Canelled = 'N' OR ORCT.Cancelled = NULL, but I dont know if that would work.

  • Query Help for reporting on last receipt qty

    SBO Version: 8.82 PL11
    Hello Forum,
    I am looking for some help devising a command behind a crystal report. We are hoping to achieve the last receipt quantity. To arrive at this we would like it to get the last GRPO for an item and total the quantity on that particular GRPO. In addition to this, we want to consider all the lines on the document and SUM them.
    At present, the query I have is as follows:
    Select SUM(c0.Quantity) from PDN1 c0 WHERE c0.ItemCode = T1.ItemCode AND Shipdate = (select Max(ShipDate) from PDN1 C0  INNER JOIN OPDN c1 ON c0.DocEntry = c1.DocEntry where C0.Itemcode =T1.ItemCode AND c1.DocStatus <> 'C'))
    Any assistance would be greatly received.
    Thanks
    Sarah

    Hi Sarah,
    Please repost to the SAP Business One Application  space.
    -Abhilash

  • SQL Query help ( On connect By level clause)

    Hi all,
    I have this query developed with data in with clause.
    With dat As
      select '@AAA @SSS @DDD' col1 from dual union all
      select '@ZZZ @XXX @TTT @RRR @ZZA' col1 from dual
    Select regexp_substr( col1 , '[^@][A-Z]+',1,level) Show from dat
    connect by level  <= regexp_count(col1, '@');Current output :-
    SHOW
    AAA
    SSS
    DDD
    RRR
    ZZA
    TTT
    RRR
    ZZA
    XXX
    DDD
    RRR
    SHOW
    ZZA
    TTT
    RRR
    ZZA
    . . .1st row comes fine, But next row data is getting duplicated. And total record count = 30. I tried with some but didn't work.
    Expected output :-
    SHOW
    AAA
    SSS
    DDD
    ZZZ
    XXX
    TTT
    RRR
    ZZAI need some change on my query and I am not able to find that. So anybody can add on that or can also provide some different solution too.
    Thanks!
    Ashutosh

    Hi,
    When you use something like "CONNECT BY LEVEL <= x", then at least one of the following must be true:
    (a) the table has no more than 1 row
    (b) there are other conditions in the CONNECT BY clause, or
    (c) you know what you are doing.
    To help see why, run this query
    SELECT     SYS_CONNECT_BY_PATH (dname, '/')     AS path
    ,     LEVEL
    FROM     scott.dept
    CONNECT BY     LEVEL <= 3
    ;and study the results:
    PATH                                     LEVEL
    /ACCOUNTING                                  1
    /ACCOUNTING/ACCOUNTING                       2
    /ACCOUNTING/ACCOUNTING/ACCOUNTING            3
    /ACCOUNTING/ACCOUNTING/RESEARCH              3
    /ACCOUNTING/ACCOUNTING/SALES                 3
    /ACCOUNTING/ACCOUNTING/OPERATIONS            3
    /ACCOUNTING/RESEARCH                         2
    /ACCOUNTING/RESEARCH/ACCOUNTING              3
    /ACCOUNTING/RESEARCH/RESEARCH                3
    /ACCOUNTING/RESEARCH/SALES                   3
    /ACCOUNTING/RESEARCH/OPERATIONS              3
    /ACCOUNTING/SALES                            2
    /ACCOUNTING/SALES/ACCOUNTING                 3
    84 rows selected.

  • Query Help required to Connect JDT1 with OINV tables

    Dear Experts,
    I have the following query which gives me the customer ageing report. I want some addtional fields from the OINV table and the document numbering table like Document Series Name, AR Invoice document Number,AR invoice remarks, BP Projects Number ( filled in accounting tab in BP projects) and in the query in Reference 1 column its giving the Invoice Numbers as posted in the Journal but for manual Journal Entries it not giving the Journal Number which I also want to be shown in Ref 1 or a seperat field.
    The Query is as under :
    select OCRD.cardcode 'Supplier Code',OCRD.cardname 'Name',sysdeb 'Debit Amount',syscred 'Credit Amount',
    case JDT1.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    else 'Other'
    end 'Type',
    Ref1,
    fccurrency 'BP Currency',
    CONVERT(VARCHAR(10), refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), duedate, 103) 'Due Date',
    CONVERT(VARCHAR(10), taxdate, 103) 'Doc Date' ,
    CASE
    when (DATEDIFF(dd,refdate,current_timestamp))+1 < 31
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "0-30 days",
    case when ((datediff(dd,refdate,current_timestamp))+1 > 30
    and (datediff(dd,refdate,current_timestamp))+1< 61)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "31 to 60 days",
    case when ((datediff(dd,refdate,current_timestamp))+1 > 60
    and (datediff(dd,refdate,current_timestamp))+1< 91)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "61 to 90 days",
    CASE
    when (DATEDIFF(dd,refdate,current_timestamp))+1 > 90
    then
    case
    when syscred= 0 then sysdeb
    when sysdeb= 0 then syscred * - 1
    end
    end "90 + days"
    from JDT1,OCRD where JDT1.shortname = OCRD.cardcode and cardtype = 'c' and intrnmatch = '0'
    ORDER BY OCRD.CARDCODE, taxdate
    Would appreciate if you can help me to get a solution in it.
    Regards,
    Kamlesh

    Dear Gordon,
    While executing the followings modified query it giving an error of
    Incorrect Syntax near the keyword 'to' and incorrect Syntax near 'Series'
    the query is as under :
    {select OCRD.cardcode 'Supplier Code',OCRD.cardname 'Name',sysdeb 'Debit Amount',syscred 'Credit Amount',
    case l.transtype
    when '13' then 'INV'
    when '14' then 'AR CN'
    when '24' then 'INCOMING'
    else 'Other'
    end 'Type',
    j.BaseRef'Trans #',
    case l.transtype
    when '13' then
    (Select Comments from OINV where OINV.Transid=j.Transid)
    else '-'
    end 'Inv.Rem.',
    (Select SeriesName From NNM1 Where Series=j.DocSeries and ObjectCode=l.TransType)'Series',
    to
    (Select Isnull(SeriesName, 'Manual') From NNM1 Where Series=j.DocSeries and ObjectCode=l.TransType)'Series',
    l.Ref1,
    fccurrency 'BP Currency',
    CONVERT(VARCHAR(10), l.refdate, 103)'Posting Date' ,
    CONVERT(VARCHAR(10), l.duedate, 103) 'Due Date',
    CONVERT(VARCHAR(10), l.taxdate, 103) 'Doc Date' ,
    CASE
    when (DATEDIFF(dd,l.refdate,current_timestamp))+1 < 31
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "0-30 days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 30
    and (datediff(dd,l.refdate,current_timestamp))+1< 61)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "31 to 60 days",
    case when ((datediff(dd,l.refdate,current_timestamp))+1 > 60
    and (datediff(dd,l.refdate,current_timestamp))+1< 91)
    then
    case
    when syscred <> 0 then syscred * - 1
    else sysdeb
    end
    end "61 to 90 days",
    CASE
    when (DATEDIFF(dd,l.refdate,current_timestamp))+1 > 90
    then
    case
    when syscred= 0 then sysdeb
    when sysdeb= 0 then syscred * - 1
    end
    end "90 + days"
    from JDT1 l
    Inner Join OJDT j On j.TransId=l.TransId
    ,OCRD where l.shortname = OCRD.cardcode and cardtype = 'c' and intrnmatch = '0'
    ORDER BY OCRD.CARDCODE, l.taxdate}
    Regards,
    Kamlesh

Maybe you are looking for