Please help SQL query

why this works fine
SELECT * FROM (
SELECT ename,deptno,sal ,ROWNUM RN FROM emp)
WHERE MOD(RN,3)=0
while
SELECT rownum FROM employees WHERE MOD(Rownum,3)=0
wotnh works
why this happenssssssssssssss

ROWNUM is dynamically determined on-the-fly during the fetching of results.
So this works:
SELECT * FROM table WHERE rownum < 11
It will return the first 10 rows. The following does not work:
SELECT * FROM table WHERE rownum between 11 and 20
As ROWNUM is added as the results are fetched from the database, it can only be used as a stopkey.
To use ROWNUM as any other column in a predicate, you need to change ROWNUM from a "dynamic on-the-fly" column into a "proper" column. Just as you did with your 1st SELECT.
E.g.WITH my_results AS(
        SELECT rownum AS RNO, o.* FROM all_objects o WHERE object_type = 'TRIGGER'
SELECT
        object_id,
        object_name
FROM    my_results
WHERE   rno between 11 and 20

Similar Messages

  • Please help in query performance

    select bg.billing_group_id,r.rating_result, count(*),rc.source,rc.description
    from rejected_record r,
    result_code@RD rc,
    terminal_device@cust td,
    personal_account_td@cust patd,
    personal_account@cust pa,
    billing_group@cust bg,
    -- tariff_plan@rd tp,
    (select pcs.primary_session_id, pcs.charging_date
    from pcs@umr_interface
    where pcs.range_cdr_file_source not like 'HOT%'
    --and lower(pcs.RANGE_CDR_FILE_SOURCE) not like 'rec%'
    -- and lower(pcs.RANGE_CDR_FILE_SOURCE) not like 'sms%'
    -- and lower(pcs.RANGE_CDR_FILE_SOURCE) not like 'data%'
    -- and pcs.CHARGING_TYPE_ID = 1
    and pcs.charging_date between '20/Aug/2010' and '21/Sep/2010') t
    where r.primary_session_id = t.primary_session_id
    and rc.code (+)= r.rating_result
    and td.terminal_device_id = patd.terminal_device_id
    and patd.personal_account_id = pa.personal_account_id
    and r.calling_party_number_rid = td.msisdn
    and pa.billing_group_id = bg.billing_group_id
    and r.is_precharged=0
    --and td.tariff_plan_id=tp.tariff_plan_id
    and (nvl(td.date_to,'01.01.2000')='01.01.2000')
    and (nvl(pa.date_to,'01.01.2000')='01.01.2000')
    and (nvl(patd.date_to,'01.01.2000')='01.01.2000')
    group by r.rating_result, rc.source, rc.description,bg.billing_group_id
    order by r.rating_result
    SQL> select * from v$version;
    BANNER
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - 64bit Production
    PL/SQL Release 9.2.0.8.0 - Production
    CORE     9.2.0.8.0     Production
    TNS for Solaris: Version 9.2.0.8.0 - Production
    NLSRTL Version 9.2.0.8.0 - Production
    SQL>
    Above select query took only 10 mins when those nvl functions where not there..
    but when these nvl fuctions are added this takes lot of time....
    please help to optimce it..
    first i tried with is null.. it took lot of time.. ten i replaced it with nvl function...
    please somebody help to optimize this query

    Check out these links:
    {message:id=1812597}
    {thread:id=863295}

  • Please Help - SQL Report long column value required in a separate cell

    Hi.
    I need to create a SQL report with the structure like below:
    Country State City Vertical Business Details (detail desc)
    US MA Quincy Healthcare
    This is a detail desc value that needs to displayed in a different cell.
    This is a detail desc value that needs to displayed in a different cell.
    This is a detail desc value that needs to displayed in a different cell.
    This is a detail desc value that needs to displayed in a different cell.
    US MA Braintree IT
    This is a detail desc value that needs to displayed in a different cell.
    This is a detail desc value that needs to displayed in a different cell.
    This is a detail desc value that needs to displayed in a different cell.
    I came through a solution where you can hide/display the long column value in a different cell. But my requirement is that it should be displayed when the page opens and user don;t want to click on a button to see the value. This is mainly for their presentations and printing. so its very annoying for them to click on so many buttons to see the detail desc value for every record. I am new to Java script, Please help

    I'm not sure I understand your requirements--are you showing us 2 lines of data, 7 lines, or 9? Do you want the long detail description on the same row, or underneath it?
    I'm going to go on the assumption that you're showing us two rows, and that the long descriptions in this example happen to be 3-4 lines long, and that you want the long descriptions underneath the details. In which case, I suggest using "named column" templates. They're a lot easier to use than they appear when you first look at them, so bear with me.
    Under "Shared Components", select "Templates", and then click on the yellow Create> button. You're creating a report template, from scratch. On the final page of the wizard, select "Named Column (row template)" for the template type. This will create a rather generic (and useless) template, which you'll have to edit; I don't know why they chose to not send you straight into the editor. When you edit it, you'll see that the only field with a value in it is "Row Template 1", and it's set to:
    <tr><td>#1#</td><td>#2#</td><td>#3#</td><td>#4#</td><td>#5#</td></tr>For meeting your requirements with basic functionality, change it to something along the lines of:
    <tr><td>#COUNTRY#</td><td>#STATE#</td><td>#CITY#</td><td>#VERT#</td></tr>
    <tr><td colspan="4">#DETAILS#</td></tr>Then you'll probably want to put something under Column Heading Template, like:
    <tr><td>Country</td><td>State</td><td>City</td><td>Vertical Business</td></tr>
    <tr><td colspan="4">Details</td></tr>Apply whatever CSS styles you want to it, of course.
    Using the template is straightforward: if your report, chose the template, and make sure your SQL returns values using the column names you specified in your template. Otherwise, you'll see literal "#COUNTRY#" text in your report.
    You can get fancy with these, of course, such as applying different styles to alternating rows, but I'll leave this as good enough to get you started (I hope).
    -David

  • Please help sql problem

    SELECT  MATNR EBELP EBELN  MENGE
                  FROM EKBE
                  INTO TABLE I_EKBE
                   FOR ALL ENTRIES IN I_EKKN_EKPO
                  WHERE EBELN EQ I_EKKN_EKPO-EBELN
                  AND   MATNR EQ I_EKKN_EKPO-MATNR
                  AND VGABE EQ '1'
                  AND BEWTP EQ 'E'
                  AND SHKZG EQ 'S'.
    when i am query in database tables i am getting 4 records
    with same condtion , but with sql query i getting 2 records .
    what is wrong with above code .
    in ekkn_ekpo there are 2 records but in ekbe table i have 4 records for that certia ( which i should get).
    it picking up unique records ( first one ).
    how get 4 records all?
    Thanks,
    sridhar

    Hi Sridhar,
    The problem is due to the FOR ALL ENTRIES usage. You have used the FOR ALL ENTRIES for EBELN and MATNR. As such, the system tries to fetch for each row, the corresponding values from the table EKBE. But when you use more than 1 field for selection, the logic breaks and hence you should try to use RANGES to read the data correctly.
    For your example, you would have to gather the MATNR from I_EKKN_EKPO internal table in a RANGES variable and then use it in the SELECT statement.
    i.e.
    RANGES: R_MAT FOR EKBE-MATNR.
    R_MAT-OPTION = 'EQ'.
    R_MAT-SIGN = 'I'.
    LOOP AT I_EKKN_EKPO.
    AT NEW MATNR.
    R_MAT-LOW = I_EKKN_EKPO-MATNR.
    APPEND R_MAT.
    ENDAT.
    ENDLOOP.
    SELECT MATNR EBELP EBELN MENGE
    FROM EKBE
    INTO TABLE I_EKBE
    FOR ALL ENTRIES IN I_EKKN_EKPO
    WHERE EBELN EQ I_EKKN_EKPO-EBELN
    AND MATNR IN R_MAT
    AND VGABE EQ '1'
    AND BEWTP EQ 'E'
    AND SHKZG EQ 'S'.
    But because you are looping thru the values of the I_EKKN_EKPO table, you might as well try the code below...
    LOOP AT I_EKKN_EKPO.
    SELECT MATNR EBELP EBELN MENGE
    FROM EKBE
    APPENDING INTO TABLE I_EKBE
    WHERE EBELN EQ I_EKKN_EKPO-EBELN
    AND MATNR EQ I_EKKN_EKPO-MATNR
    AND VGABE EQ '1'
    AND BEWTP EQ 'E'
    AND SHKZG EQ 'S'.
    ENDLOOP. " I_EKKN_EKPO.
    Personally, I would advise you to go with the option 1 as it will work faster. *** SELECTs within LOOP generally work slower when the iterations increase.
    Hope this helps.
    Chaps.

  • Please Help in query

    SELECT PEE2.ASSIGNMENT_ID,--,PEEV2.EFFECTIVE_START_DATE,
    PET.ELEMENT_NAME,NVL(MAX(PEEV2.SCREEN_ENTRY_VALUE),0)SALARY
    --PEE2.EFFECTIVE_START_DATE PEE_START
    FROM PAY_ELEMENT_ENTRIES_F PEE2,PAY_ELEMENT_ENTRY_VALUES_F PEEV2 , PAY_ELEMENT_TYPES_F PET
    WHERE PEE2.ELEMENT_TYPE_ID = PET.ELEMENT_TYPE_ID
    AND PEE2.ELEMENT_ENTRY_ID=PEEV2.ELEMENT_ENTRY_ID
    AND PET.ELEMENT_NAME IN('BASIC_SALARY','AL_CONVEYANCE','AL_TEA','AL_COLA')
    AND PEEV2.SCREEN_ENTRY_VALUE IS NOT NULL
    AND (PEE2.ASSIGNMENT_ID,PEEV2.EFFECTIVE_START_DATE)=(
    SELECT PEE.ASSIGNMENT_ID,MAX(PEEV.EFFECTIVE_START_DATE)
    FROM PAY_ELEMENT_ENTRIES_F PEE,PAY_ELEMENT_ENTRY_VALUES_F PEEV
    WHERE PEE.ELEMENT_ENTRY_ID=PEEV.ELEMENT_ENTRY_ID
    AND PEE.ASSIGNMENT_ID=:ASSIGNMENT_ID
    AND PEE.ELEMENT_TYPE_ID = PET.ELEMENT_TYPE_ID
    AND PET.ELEMENT_NAME IN('BASIC_SALARY','AL_CONVEYANCE','AL_TEA','AL_COLA')
    AND PEEV.SCREEN_ENTRY_VALUE IS NOT NULL
    GROUP BY PEE.ASSIGNMENT_ID
    )GROUP BY ASSIGNMENT_ID , PET.ELEMENT_TYPE_ID , PET.ELEMENT_NAME
    output is
    ASSIGNMENT_ID     ELEMENT_NAME     SALARY
    117     AL_COLA     650
    117     AL_CONVEYANCE     1180
    117     AL_TEA     172
    117     BASIC_SALARY     7820
    but i want the output like this
    ASSIGNMENT_ID ------AL_COLA------AL_CONVEYANCE------AL_TEA-------BASIC_SALARY
    117---------------------------650-------------------1180----------------------172-----------7820
    PLZZ HELP NO HARDCODE PLZZ ONLY DYNAMIC QUERY REQUIRED AND NO PL/SQL USED..
    REGARDS
    RANCHOO

    Hi,
    Since you didn't post any tables, I'll use the scott.emp table to show you how to get results like that.
    Let's say we're interested in this data:
    SELECT       deptno
    ,       job
    ,       sal
    FROM       scott.emp
    ORDER BY  deptno
    ,     job
        DEPTNO JOB              SAL
            10 CLERK           1300
            10 MANAGER         2450
            10 PRESIDENT       5000
            20 ANALYST         3000
            20 ANALYST         3000
            20 CLERK           1100
            20 CLERK            800
            20 MANAGER         2975
            30 CLERK            950
            30 MANAGER         2850
            30 SALESMAN        1250
            30 SALESMAN        1250
            30 SALESMAN        1600
            30 SALESMAN        1500Let's say we want to get a total sal for each deptno and job, aned present it as a cross-tab, with a row for every deptno and a column for every job. As Karthick pointed out, that requires dynamic SQL, so let's just take the first 4 jobs in alphabetic order. The query below numbers the jobs 1, 2, 3, ... in alphabetic order, then uses that number to consider only a certain job in each column.
    WITH     got_jnum    AS
         SELECT       deptno
         ,       job
         ,       sal
         ,       DENSE_RANK () OVER (ORDER BY job)     AS jnum
         FROM       scott.emp
    SELECT       deptno
    ,       TO_CHAR (SUM (CASE WHEN jnum = 1 THEN sal END), '99999999')     AS job_1
    ,       TO_CHAR (SUM (CASE WHEN jnum = 2 THEN sal END), '99999999')     AS job_2
    ,       TO_CHAR (SUM (CASE WHEN jnum = 3 THEN sal END), '99999999')     AS job_3
    ,       TO_CHAR (SUM (CASE WHEN jnum = 4 THEN sal END), '99999999')     AS job_4
    FROM       got_jnum
    GROUP BY  deptno
        UNION ALL
    SELECT       NULL                                   AS deptno
    ,       MIN (CASE WHEN jnum = 1 THEN LPAD (job, 9) END)     AS job_1
    ,       MIN (CASE WHEN jnum = 2 THEN LPAD (job, 9) END)     AS job_2
    ,       MIN (CASE WHEN jnum = 3 THEN LPAD (job, 9) END)     AS job_3
    ,       MIN (CASE WHEN jnum = 4 THEN LPAD (job, 9) END)     AS job_4
    FROM       got_jnum
    ORDER BY  deptno     NULLS FIRST
        DEPTNO JOB_1     JOB_2     JOB_3     JOB_4
                 ANALYST     CLERK   MANAGER PRESIDENT
            10                1300      2450      5000
            20      6000      1900      2975
            30                 950      2850A lot of the complexity in the query above involves getting the row with the actual job names. If you knew what they were, you could hard-colde them into the query; then you woldn't need the second part of the UNION, and therefore you wouldn't need TO_CHAR.
    This is called a Pivot . Search for "Pivot" (or, as Karthick suggested "Rows to Columns") to see more examples and explanations.
    If you really want a variable number of columns, then you need dynamic SQL, as Karthick explained. This isn't very hard, as dynamic SQL goes. You just need to have a preliminary query determine what the jobs are, and write an appropriate SUM expression (with column alias) to use in the SELECT clause. See [this thread|http://forums.oracle.com/forums/message.jspa?messageID=3227306] for an example.
    Another way to get a variable number of jobs is to use String Aggregation , where all the data about all the jobs is combined in one giant string column. That huge string can be formatted so that it looks like separate columns. [This site|http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php] has a good summary of different String Aggregation techniques.

  • Please help - Recursive Query Restrictions

    Hi All,
    I wanted to know what restrictions are placed on Oracle Recursive Query capability. Any help or links in this regards would be highly appreciated. Waiting to hear from you.
    Thanks,
    Snehal

    Can't think of anything I would term a restriction off the top of my head. There are a few notes in the SQL Reference about precedence that probably aren't obvious.
    Are you having a particular problem with this syntax?
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Please help with query

    Hello, I'm trying to write a query which is of the form below:
    select (aa.name || bb.name) full_name
    from
    (select * from per_positions where name = 'Igwe') aa,
    (select * from per_positions where name = 'OSHS.Application.Specialist.Head Office') bb
    There are two generated tables aa and bb. Sometimes aa and bb both return a value and sometimes only aa or only bb returns a value. So my question is, in a scenario where only of the inner tables returns a value, is it possible to make the other table return a null or blank value? In my case, when one of the tables doesn't return a value the entire record shows a null value. Thanks.

    user FULL JOIN
    SQL> with t
      2  as
      3  (select 'a' name from dual
      4  union all
      5  select 'b' name from dual
      6  )
      7  select aa.name||bb.name
      8    from (select name from t where name = 'a') aa
      9    full join (select name from t where name = 'b') bb
    10      on 1=1
    11  /
    AA
    ab
    SQL> with t
      2  as
      3  (select 'a' name from dual
      4  union all
      5  select 'b' name from dual
      6  )
      7  select aa.name||bb.name
      8    from (select name from t where name = 'a') aa
      9    full join (select name from t where name = 'x') bb
    10      on 1=1
    11  /
    AA
    a
    SQL> with t
      2  as
      3  (select 'a' name from dual
      4  union all
      5  select 'b' name from dual
      6  )
      7  select aa.name||bb.name
      8    from (select name from t where name = 'x') aa
      9    full join (select name from t where name = 'b') bb
    10      on 1=1
    11  /
    AA
    b

  • Please help with query for 5 lastest opening balance  !!!!!!!!!!!

    Can anyone plese tell me or guide me how to write the query to show the 5 lastest opening balance from the A/R invoice on the specific BP partner?
    Example
    The box to input "BP partner"
    and then show,
    Lastest transaction | Ship date | Invoice number | Balance Amount | Culmulative
    1    
    2
    3
    4
    5
    Your help will be very very appreciated.

    This is very good but I would like to show only the top 5 remaining invoice. I think that I have to combine it with JDT1. I have seen one query that may be able to apply on my case.
    SELECT
    T1.CardCode + '' AS 'BP Code',
    T2.Notes2 AS 'BP Name',
    T0.RefDate,
    CASE
         WHEN T0.TransType = 13 THEN 'IN'
         WHEN T0.TransType = 14 THEN 'CN'
         WHEN T0.TransType = 30 THEN 'JE'
         WHEN T0.TransType = 24 THEN 'RC'
         WHEN T0.TransType = 46 THEN 'PS'
         ELSE 'Error ! ! !'
    END AS 'Doc Type',
    T0.Ref1 'Doc. Number',
    ISNULL(T0.FCCurrency, ' - ') AS 'Ccy',
    (T0.BalFcDeb - T0.BalFcCred) AS 'Bal. F. Ccy',
    (T0.BalDueDeb - T0.BalDueCred) AS 'Bal. Rs',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') <= -1)                     ,0) AS 'Future',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') = 0)                         ,0) AS 'Current Mth',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') = 1)                         ,0) AS '1 Mth Ago',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') = 2)                         ,0) AS '2 Mth Ago',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate ,'[%1]') = 3)                         ,0) AS '3 Mth Ago',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') between 4 and 6)    ,0) AS '4 - 6 Mth Ago',
    ISNULL((SELECT T0.BalDueDeb -T0.BalDueCred WHERE DateDiff(mm, T0.RefDate, '[%1]') >= 7)                       ,0) AS '>7 Mth Ago'
    FROM JDT1 T0
    INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    LEFT OUTER JOIN OCPR T2 ON T1.CardCode = T2.Cardcode
    LEFT OUTER JOIN OJDT T3 ON T0.TransID = T3.TransID
    LEFT OUTER JOIN OINV  T4 ON T3.TransID = T4.TransID
    LEFT OUTER JOIN ORIN  T5 ON T3.TransID = T5.TransID
    WHERE
    T1.CardType = 'C' and Balance != 0
    and (T0.BalDueDeb - T0.BalDueCred) != 0
    but still try to figure it out....

  • Help SQL Query (Not working as it should)

    Hello everybody,
    I'm using JDeveloper 12.1.2.0.0 . I'm doing a bidirectional comunication using 3 tables, with bindings between them (and using HR schema).
    In my example, i have something like:
    Departments, Employees and SalaryByJobs (i created this table where it shows the departmentd id, employee id, job, salary).
    Whenever i click on one OR more departments, the employees table update by putting on the table, the employees that belong to the selected department and the salaryByjob put the jobs by employees selected on the employees table.
    So it's something like this:
    Departments selected -> employees selected -> salarybyjbobs of those employees.
    My Employees query (in the view) has the following code:
    SELECT Employees.COMMISSION_PCT,
           Employees.DEPARTMENT_ID,
           Employees.EMAIL,
           Employees.EMPLOYEE_ID,
           Employees.FIRST_NAME,
           Employees.HIRE_DATE,
           Employees.JOB_ID,
           Employees.LAST_NAME,
           Employees.MANAGER_ID,
           Employees.PHONE_NUMBER,
           Employees.SALARY
    FROM  EMPLOYEES Employees
    WHERE ( DEPARTMENT_ID IN (select * from THE(select cast( in_list(:variavel3) as mytableType ) from dual ) a))
    Since i use bindings, the employees table don't show anything in the beginning, so i added this parte to my employees query: OR nvl(:variavel3,0) = 0
    But now, whenever i try to select more than one row, it gives me invalid numbers and i don't understand why..
    It's only more one line of code and it's not in the bean.
    Can anyone help me?
    Ps - The bean goes department by department, appends the departments with "," and for each department, gets the employees that belongs to them.
    My best regards,
    Frederico Barracha.

    The expression NVL(:variavel3,0)=0 is not correct. The datatype of the return value of the NVL function is considered equal to the datatype of the 1st argument (i.e to the datatype of the bind variable :variavel3). You said that this variable contained a comma-separated list of IDs, so the variable's datatype is VARCHAR2. As far as you are comparing the NVL-expression to a number, you get "Invalid number" exception, because Oracle is expecting a numeric datatype at the left side of the comparison operator.
    In order to avoid the "Invalid number" exception you can modify the expression using one of the following options:
    :variavel3 IS NULL
    NVL( :variavel3, '*' ) = '*'
    NVL( :variavel3, '0' ) = '0'
    The 1st option if the simplest and the most clear one.
    Dimitar

  • Please Help this query should be simple :)

    Here is what I have written so far: Basically I want it to return all the locations like I have specified that do not have DA-REPL in the area_code table but it is just returning everything it seems.
    select l.location_no, l.zone_code, la.area_code
    from move.location l, move.location_area la
    where la.location_no = l.location_no
    and l.zone_code = 'Z-BIN'
    and (l.location_no like '%%-%%-2%%' or l.location_no like '%%-%%-1%%')
    and la.area_code != 'DA-REPL'
    order by 1
    Here is what my results look like:
    60-02-101     Z-BIN     WA-60
    60-02-101     Z-BIN     WA-BIN
    60-02-101     Z-BIN     WA-BINRESV
    60-02-101     Z-BIN     WA-PALLET
    60-02-102     Z-BIN     WA-60
    60-02-102     Z-BIN     WA-BIN
    60-02-102     Z-BIN     WA-BINRESV
    60-02-102     Z-BIN     WA-PALLET
    60-02-201     Z-BIN     WA-60
    60-02-201     Z-BIN     WA-BIN
    60-02-201     Z-BIN     WA-BINRESV
    60-02-201     Z-BIN     WA-PALLET
    Edited by: 906043 on Feb 20, 2012 2:23 PM

    906043 wrote:
    At it's most basic the query would look like this but this gives me 67,834 results I am dealing with a pretty big warehouse with many "la.area_code" entries I am only trying to get the locations in a specific zone('Z-BIN') that do not have 'DA-REPL' as an la.area_code as this would cause that location never to get replenishments when it becomes empty.
    select l.location_no, l.zone_code, la.area_code
    from move.location l, move.location_area la
    where la.location_no = l.location_no
    l.zone_code = 'Z=BIN'
    and la.area_code != 'DA-REPL'
    order by 1
    Not sure if that helps anymore I am at a loss but still plugging away :)A little attention to code formatting could bring some sanity to yourself. Enclosing that formatted code in the code tags on this forum would bring a lot of sanity to those trying to help you:
    select l.location_no
    ,      l.zone_code
    ,      la.area_code
    from move.location l
    ,    move.location_area la
    where la.location_no = l.location_no
          l.zone_code = 'Z=BIN'
    and   la.area_code != 'DA-REPL'
    order by 1And once it is formatted for easier reading by humans, it's easier to see that you are missing an "and" (maybe "or"?) in your WHERE clause.

  • Need help - sql query

    Hi,
         I have two tables(production & sales). I want to generate monthly statement. The followings are the sample data.
    PRODUCTION:
    DATE          MATERIAL     WEIGHT      AMOUNT
    01/12/2008     Item1     300     6000
    03/12/2008     item2          250      3500
    07/12/2008     item3          700     6500
    12/12/2008     item1          200     4000
    20/12/2008     item3          400     9600
    25/12/2008     item1          250     5000
    Sales:
    SAL_Date          Sal_Material     sal_weight     SAL_Amount
    12/12/2008     item3          270     2300
    15/12/2008     item1          200     4000
    20/12/2008     item2          250     3500
    20/12/2008     item1          100     2000
    23/12/2008     item1          100     2000
    27/12/2008     item3          200     3500
    I want to generate monthly statement like the following....
    Required Report:
    Date          Production          Sales
              Weight - Amount      Weight - Amount          
    01/12/2008     300     6000          0     0
    02/12/2008     0     0     0     0
    03/12/2008     250     3500          0     0           
    04/12/2008     0 0 0 0
    07/12/2008     700 6500 0 0
    12/12/2008     200     4000     270 2300
    31/12/2008 0 0 0 0
    i don't know, how to generate sequential date...
    Could you please tell me the query?
    Thanks & Regards

    SQL> with prod
      2  as
      3  (
      4     select to_date('01/12/2008','dd/mm/yyyy') dt, 'Item1' material, 300 weight, 6000 amount from dual union all
      5     select to_date('03/12/2008','dd/mm/yyyy'), 'item2', 250, 3500 from dual union all
      6     select to_date('07/12/2008','dd/mm/yyyy'), 'item3', 700, 6500 from dual union all
      7     select to_date('12/12/2008','dd/mm/yyyy'), 'item1', 200, 4000 from dual union all
      8     select to_date('20/12/2008','dd/mm/yyyy'), 'item3', 400, 9600 from dual union all
      9     select to_date('25/12/2008','dd/mm/yyyy'), 'item1', 250, 5000 from dual
    10  ), sales
    11  as
    12  (
    13     select to_date('12/12/2008','dd/mm/yyyy') dt, 'item3' material, 270 weight, 2300 amount from dual union all
    14     select to_date('15/12/2008','dd/mm/yyyy'), 'item1', 200, 4000 from dual union all
    15     select to_date('20/12/2008','dd/mm/yyyy'), 'item2', 250, 3500 from dual union all
    16     select to_date('20/12/2008','dd/mm/yyyy'), 'item1', 100, 2000 from dual union all
    17     select to_date('23/12/2008','dd/mm/yyyy'), 'item1', 100, 2000 from dual union all
    18     select to_date('27/12/2008','dd/mm/yyyy'), 'item3', 200, 3500 from dual
    19  ),find_date
    20  as
    21  (
    22     select dt st, last_day(dt) ed
    23       from (select distinct trunc(dt,'month') dt from prod
    24             union
    25             select distinct trunc(dt,'month') dt from sales)
    26  ),day_list
    27  as
    28  (
    29     select (level-1)+st dt
    30       from find_date
    31     connect by level <= (ed - st)+1
    32  )
    33  select d.dt, t.p_weight, t.p_amount, t.s_weight, t.s_amount
    34    from day_list d
    35    left join
    36         (select decode(p.dt,null,s.dt,p.dt) dt,
    37                    sum(p.weight) p_weight, sum(p.amount) p_amount, sum(s.weight) s_weight, sum(s.amount) s_amount
    38            from prod p
    39            full outer join sales s
    40              on p.dt = s.dt
    41             and p.material = s.material
    42           group by decode(p.dt,null,s.dt,p.dt)) t
    43      on d.dt = t.dt
    44  order by d.dt
    45  /
    DT          P_WEIGHT   P_AMOUNT   S_WEIGHT   S_AMOUNT
    01-DEC-08        300       6000
    02-DEC-08
    03-DEC-08        250       3500
    04-DEC-08
    05-DEC-08
    06-DEC-08
    07-DEC-08        700       6500
    08-DEC-08
    09-DEC-08
    10-DEC-08
    11-DEC-08
    DT          P_WEIGHT   P_AMOUNT   S_WEIGHT   S_AMOUNT
    12-DEC-08        200       4000        270       2300
    13-DEC-08
    14-DEC-08
    15-DEC-08                              200       4000
    16-DEC-08
    17-DEC-08
    18-DEC-08
    19-DEC-08
    20-DEC-08        400       9600        350       5500
    21-DEC-08
    22-DEC-08
    DT          P_WEIGHT   P_AMOUNT   S_WEIGHT   S_AMOUNT
    23-DEC-08                              100       2000
    24-DEC-08
    25-DEC-08        250       5000
    26-DEC-08
    27-DEC-08                              200       3500
    28-DEC-08
    29-DEC-08
    30-DEC-08
    31-DEC-08
    31 rows selected.

  • Nees Help: Sql Query

    [http://www.srikanthtechnologies.com/oracle/dec9/hrqueries.html] Learning sql.
    From HR Model : Find employees with the highest salary from each country.
    HR model link is attached.
    Edited by: 999344 on Apr 10, 2013 1:16 PM

    Hi,
    Welcome to the forum!
    999344 wrote:
    Learning sql.
    From HR Model : Find employees with the highest salary from each country.That;s an example of a Top-N Query . Search for "top-n query" and you;ll get lots of examples, such as {message:id=3739578}
    HR model link is attached.Really?

  • Help: SQL query when parsed returns Invalid Identifier error

    Hi The expression posted below is the actual SQL Expression which is required in my report:
    ((select name from (
    select loc_id,name,row_number()over(  order by r)  rn from (
    SELECT 0, loc_id, Misc1_txt  NAME,'A' STATUS ,rownum r
                        FROM dvxloc
                       WHERE loc_id = "XXXLOC"."LOC_ID"
                       union
    SELECT     parent_loc_id, loc_id, (SELECT a.Misc1_txt
                                                         FROM dvxloc a
                                                        WHERE a.loc_id =b.loc_id) NAME,'B' ,ROWNUM
                            FROM dvxlocpath b
                      START WITH b.loc_id = "XXXLOC"."LOC_ID"
                      CONNECT BY PRIOR  parent_loc_id=loc_id
    )                where name is NOT NULL        order by STATUS, R
    ) where rn = 1))
    It gives an error while parsing: "XXXLOC"."LOC_ID" invalid identifier
    LOC_ID is of numeric data type in the database. and when I run thi query in SQL editor after replacing "XXXLOC"."LOC_ID" with a numeric value say 456 . The query can be put as
    ((select name from (
    select loc_id,name,row_number()over(  order by r)  rn from (
    SELECT 0, loc_id, Misc1_txt  NAME,'A' STATUS ,rownum r
                        FROM dvxloc
                       WHERE loc_id = 456                   union
    SELECT     parent_loc_id, loc_id, (SELECT a.Misc1_txt
                                                         FROM dvxloc a
                                                        WHERE a.loc_id =b.loc_id) NAME,'B' ,ROWNUM
                            FROM dvxlocpath b
                      START WITH b.loc_id = 456                  CONNECT BY PRIOR  parent_loc_id=loc_id
    )                where name is NOT NULL        order by STATUS, R
    ) where rn = 1))
    The above query runs flawlessly in a SQL editor. and also this is parsed by the crystal sql expression editer
    I'm totally messed up of looking for altenatives. I have to deliver a report to the client and stuck on this part only.
    The below query parses perfectly in crystal:
    (select locname
    from dvxloc where loc_id in(select loc3 from dvxlocpath
    where loc_id = "XXXLOC"."LOC_ID"))
    Edited by: vipulbhatia29 on May 8, 2009 11:06 AM
    Edited by: vipulbhatia29 on May 8, 2009 11:14 AM

    You said the above works in SQL Editor but does your original work?
    ((select name from (
    select loc_id,name,row_number()over( order by r) rn from (
    SELECT 0, loc_id, Misc1_txt NAME,'A' STATUS ,rownum r
    FROM dvxloc
    WHERE loc_id = "XXXLOC"."LOC_ID"
    union
    SELECT parent_loc_id, loc_id, (SELECT a.Misc1_txt
    FROM dvxloc a
    WHERE a.loc_id =b.loc_id) NAME,'B' ,ROWNUM
    FROM dvxlocpath b
    START WITH b.loc_id = "XXXLOC"."LOC_ID"
    CONNECT BY PRIOR parent_loc_id=loc_id
    ) where name is NOT NULL order by STATUS, R
    ) where rn = 1))
    Crystal does nothing to the SQL in the command editor, what you type in is what we pass.
    What database are you connecting to? And if it has a tracing tool what SQL are you seeing from Crystal when you try to run the report?

  • Please help, simple query not working

    Have the following script that I would like to run at multiple sites and create table columns if necessary:
    DECLARE
    table_name VARCHAR2 (30) := 'SITE_STATISTICS';
    column_name VARCHAR2 (30) := 'SITE_MONTH';
    column_data_type VARCHAR2 (30) := 'DATE';
    column_count INTEGER;
    dynamic_sql VARCHAR2 (4000);
    BEGIN
    SELECT COUNT (1)
    INTO column_count
    FROM SYS.USER_TAB_COLUMNS utc
    WHERE utc.table_name = table_name AND utc.column_name = column_name AND utc.data_type = column_data_type;
    SYS.DBMS_OUTPUT.ENABLE (4000);
    IF column_count = 0 THEN
    dynamic_sql :=
    ALTER TABLE SITE_STATISTICS ADD (SITE_MONTH DATE);
    EXECUTE IMMEDIATE dynamic_sql;
    ELSE
    DBMS_OUTPUT.put_line ('Not running Dynamic Sql, found ' || column_count || ' corresponding rows in sys.user_tab_columns');
    END IF;
    END;
    EXIT;
    At a given site I do not have the given column, and running the select from sys.user_tab_columns manually returns 0 rows. However, when I run this script it outputs the following:
    Not running Dynamic Sql, found 128 corresponding rows in sys.user_tab_columns
    What's going on!?

    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining options
    SQL> create table abc (c1 number(10));
    Table created.
    SQL> DECLARE
      2     table_name1                   VARCHAR2 ( 30 ) := 'ABC';
      3     column_name1                  VARCHAR2 ( 30 ) := 'SITE_MONTH';
      4     column_data_type1             VARCHAR2 ( 30 ) := 'DATE';
      5     column_count                  INTEGER;
      6     dynamic_sql                   VARCHAR2 ( 4000 );
      7  BEGIN
      8     SELECT COUNT ( 1 )
      9       INTO column_count
    10       FROM SYS.user_tab_columns utc
    11      WHERE utc.table_name = table_name1
    12        AND utc.column_name = column_name1
    13        AND utc.data_type = column_data_type1;
    14  
    15     SYS.DBMS_OUTPUT.ENABLE ( 4000 );
    16  
    17     IF column_count = 0 THEN
    18  
    19        dynamic_sql :='ALTER TABLE ABC ADD (SITE_MONTH DATE,SHIP_CONTANK INTEGER,SHIP_CONRAIL INTEGER)';
    20  
    21        EXECUTE IMMEDIATE dynamic_sql;
    22     ELSE
    23        DBMS_OUTPUT.put_line (    'Not running Dynamic Sql, found '
    24                               || column_count
    25                               || ' corresponding rows in sys.user_tab_columns'
    26                             );
    27     END IF;
    28  END;
    29  /
    PL/SQL procedure successfully completed.
    SQL> desc abc
    Name                                      Null?    Type
    C1                                                 NUMBER(10)
    SITE_MONTH                                         DATE
    SHIP_CONTANK                                       NUMBER(38)
    SHIP_CONRAIL                                       NUMBER(38)

  • Please help -- MySQL Query to Oracle

    I have been trying to convert the following MySQL query to work with Oracle 9i. There seem to be two problems:
    1) Oracle doesn't like the inclusion of the tblpackagegeneral.packageid in the "ON" clause of the "JOIN".
    2) The "GROUP BY" only has the one field, "tblpackagegeneral.packageid", specified; Oracle wants the other two specified as well. When I do that I get a different data set than what MySQL returns for the same tables of data: specifically MySQL returns one row for each packageid but the revised Oracle version returns more than 1 sometimes.
    I would appreciate any assistance possible.
    /* Formatted on 2003/07/07 14:43 (Formatter Plus v4.8.0) */
    SELECT tblpackagegeneral.packageid,
    CASE
    WHEN NVL
    (COUNT (tblpackagelearnerassignment.learnerid),
    COUNT (tbllearnergeneral.learnerid)
    ) > 0
    THEN 'Activity'
    WHEN tbllearnergeneral.subscribetopubliccourse = 'true'
    AND tblpackagegeneral.packageaccess = 'Public'
    THEN 'ActivityAfterSubscribe'
    WHEN ( tbllearnergeneral.subscribetopubliccourse = 'false'
    AND tblpackagegeneral.packageaccess = 'Public'
    THEN 'Subscribe'
    ELSE 'Subscribe'
    END AS "ASSIGNSTATUS"
    FROM tblpackagegeneral, tbllearnergeneral LEFT OUTER JOIN tblpackagelearnerassignment ON ( tblpackagelearnerassignment.packageid =
    tblpackagegeneral.packageid
    AND tblpackagelearnerassignment.learnerid =
    tbllearnergeneral.learnerid
    WHERE tbllearnergeneral.learnerid = '%var'
    AND tblpackagegeneral.packageavailability = 'Available'
    AND TO_CHAR (tblpackagegeneral.dateto, 'YYYYMMDD') >=
    TO_CHAR (CURRENT_TIMESTAMP, 'YYYYMMDD')
    GROUP BY tblpackagegeneral.packageid;
    Sincerely,
    Bill Robinson

    I have been trying to convert the following MySQL query to work with Oracle 9i. There seem to be two problems:
    1) Oracle doesn't like the inclusion of the tblpackagegeneral.packageid in the "ON" clause of the "JOIN".
    2) The "GROUP BY" only has the one field, "tblpackagegeneral.packageid", specified; Oracle wants the other two specified as well. When I do that I get a different data set than what MySQL returns for the same tables of data: specifically MySQL returns one row for each packageid but the revised Oracle version returns more than 1 sometimes.
    I would appreciate any assistance possible.
    /* Formatted on 2003/07/07 14:43 (Formatter Plus v4.8.0) */
    SELECT tblpackagegeneral.packageid,
    CASE
    WHEN NVL
    (COUNT (tblpackagelearnerassignment.learnerid),
    COUNT (tbllearnergeneral.learnerid)
    ) > 0
    THEN 'Activity'
    WHEN tbllearnergeneral.subscribetopubliccourse = 'true'
    AND tblpackagegeneral.packageaccess = 'Public'
    THEN 'ActivityAfterSubscribe'
    WHEN ( tbllearnergeneral.subscribetopubliccourse = 'false'
    AND tblpackagegeneral.packageaccess = 'Public'
    THEN 'Subscribe'
    ELSE 'Subscribe'
    END AS "ASSIGNSTATUS"
    FROM tblpackagegeneral, tbllearnergeneral LEFT OUTER JOIN tblpackagelearnerassignment ON ( tblpackagelearnerassignment.packageid =
    tblpackagegeneral.packageid
    AND tblpackagelearnerassignment.learnerid =
    tbllearnergeneral.learnerid
    WHERE tbllearnergeneral.learnerid = '%var'
    AND tblpackagegeneral.packageavailability = 'Available'
    AND TO_CHAR (tblpackagegeneral.dateto, 'YYYYMMDD') >=
    TO_CHAR (CURRENT_TIMESTAMP, 'YYYYMMDD')
    GROUP BY tblpackagegeneral.packageid;
    Sincerely,
    Bill Robinson

Maybe you are looking for