Query for 3 tables.

Hi,
I need to write a SELECT statement that returns one row for each customer that has orders with the following columns:
======================================================================
Email addresses from Customers Table
Sum of the Item Price in the OrdersItems table multiplied by the quantity in the
OrderItems table
Sum of the discount amount column in the OrderItems table multiplied by the quantity in the OrderItems Table.
Sort the results set in the descending sequence by the item price total for each customer.
===================================================================
Customers table has no connection with Orderitems table, so it has to go through ORDERS table.  I have written the following query. Can someone check and give me a feed back? It is not giving me the correct output. This should be the output:
Email address                                        
ItemPriceTotal                                DiscountAmountTotal
[email protected]                   4131.00                                             
1830.30
etc, etc........
My code is not adding the above columns correctly. I have tried SUM for Total columns but gives me errors:
SELECT EmailAddress, ItemPrice * Quantity AS ItemPriceTotal, DiscountAmount * Quantity AS DiscountAmountTotal
FROM
Customers
 JOIN ORDERS
ON CUSTOMERS.CustomerID = Orders.CustomerID  ----Joins Orders with Customers
JOIN OrderItems
ON Orders.OrderID = OrderItems.OrderID; ------ Joins Orders with OrderItems
----ORDER BY EmailAddress,ItemPriceTotal;  ( tried Order by, but output is not correct)

Thank you for your help. I really appreciate it. My output should look like this, but my query is not adding the ItemPriceTotal and DiscountAmountTotal:
Results:
EmailAddress
ItemPriceTotal
DiscountAmountTotal
[email protected]
4131.00
1830.39
[email protected]
2398.00
719.40
[email protected]
2198.98
659.70
[email protected]
998.00
209.70
[email protected]
799.99
120.00
[email protected]
489.99
186.20
[email protected]
299.00
0.00

Similar Messages

  • EA3: Bug in dependencies query for table tab

    SQL Developer 1.5EA3, JDK 1.6.0_04
    I have just noticed a problem with the dependencies query on the table tab - it only shows dependencies where the referencing object is owned by the table owner and for any object with the same name as the table owner.
    The query is:
    sselect owner, name, type, referenced_owner, referenced_name, referenced_type ,owner sdev_link_owner, name sdev_link_name, type sdev_link_type from ALL_DEPENDENCIES where owner = :OBJECT_OWNER and referenced_name = :OBJECT_NAME
    Instead of restricting owner to :OBJECT_OWNER, it should be restricting referenced_owner to :OBJECT_OWNER.
    theFurryOne

    I think the arrow keys could be used for navigating the grid, and Alt-Down Arrow and Alt-Up Arrow could be used for viewing the drop-down list.
    How about instead of allowing someone to type in the value, have them select from a list? The index columns can only be columns on the table, and if a column is already chosen for the index, remove it from the list.
    I think the behavior of Microsoft's Table Designer is similiar.
    What do you think?

  • SIngle query for table Update

    In a procedure I have a CURSOR FOR_LOOP
      FOR CUR_CONTO in
         (SELECT TO_NUMBER(lpad(nvl(ltrim(K_DRG),'0'),3,'0')   ) K_DRG,
             CASE
            WHEN K_MDC  = 'NA' THEN 0
             WHEN K_MDC <> 'NA' THEN TO_NUMBER( lpad(nvl(ltrim(K_MDC),'0'),2,'0')   )
             END K_MDC,
                     TO_NUMBER(substr(PAZIENTE,     instr(PAZIENTE,'@')+1, 4) ) KCODET, 
                     substr(PAZIENTE,     instr(PAZIENTE,'@')+5, 1)           TIPORDT,  
                     TO_NUMBER(SUBSTR(N_CCLINICA,1,4) )                      ANNOT
                FROM table_g)
         LOOP
         UPDATE table_dm SET K_DRG = CUR_CONTO.K_DRG , K_MDC = NVL(CUR_CONTO.K_MDC,0)
                        WHERE  K_CODE  = CUR_CONTO.KCODET
                        AND    TIPORD  = CUR_CONTO.TIPORDT
                        AND    ANNO    = CUR_CONTO.ANNOT ;
         end  LOOP;
      I want change it in a single query, how can I do?
    I write
    UPDATE table_dm SET K_DRG , K_MDC =
        (SELECT     TO_NUMBER(lpad(nvl(ltrim(K_DRG),'0'),3,'0')   ) K_DRG,
             CASE
            WHEN K_MDC  = 'NA' THEN 0
             WHEN K_MDC <> 'NA' THEN TO_NUMBER( lpad(nvl(ltrim(K_MDC),'0'),2,'0')   )
             END K_MDC FROM table_g )
                but I don't know how insert in the where the variable KCODET, TIPORDT ,ANNOT get from table table_g
    WHERE K_CODE = CUR_CONTO.KCODET
    AND TIPORD = CUR_CONTO.TIPORDT
    AND ANNO = CUR_CONTO.ANNOT ;
    And How can I lock table_dm because it has some trigger in updating?
    Thanks in advance

    It should be something like this
    UPDATE table_dm dm
        SET (K_DRG, K_MDC) = (
                    SELECT k_drg, NVL(k_mdc,0)
                      FROM (SELECT TO_NUMBER(lpad(nvl(ltrim(K_DRG),'0'),3,'0')   ) k_drg,
                             CASE
                                  WHEN k_mdc  =  'NA' THEN 0
                                  WHEN k_mdc  != 'NA' THEN TO_NUMBER( lpad(nvl(ltrim(k_mdc),'0'),2,'0'))
                             END k_mdc,
                             TO_NUMBER(substr(paziente, instr(paziente,'@')+1, 4)) kcodet, 
                             substr(paziente, instr(paziente,'@')+5, 1) tipordt,  
                             TO_NUMBER(SUBSTR(n_cclinica,1,4)) annot
                           FROM table_g) t
                     WHERE t.kcodet  = dm.k_code
                       AND t.tipordt = dm.tipord
                       AND t.annot   = dm.annot
      WHERE EXISTS (
               SELECT null
                 FROM (SELECT TO_NUMBER(lpad(nvl(ltrim(K_DRG),'0'),3,'0')   ) k_drg,
                        CASE
                             WHEN k_mdc  =  'NA' THEN 0
                             WHEN k_mdc  != 'NA' THEN TO_NUMBER( lpad(nvl(ltrim(k_mdc),'0'),2,'0'))
                        END k_mdc,
                        TO_NUMBER(substr(paziente, instr(paziente,'@')+1, 4)) kcodet, 
                        substr(paziente, instr(paziente,'@')+5, 1) tipordt,  
                        TO_NUMBER(SUBSTR(n_cclinica,1,4)) annot
                      FROM table_g) t
                WHERE t.kcodet  = dm.k_code
                  AND t.tipordt = dm.tipord
                  AND t.annot   = dm.annot
                )Note: Code not tested

  • Query for Tables used in a Schema

    I need to know that how many tables in the schema has been used by Proceudres/Functions, Packages Triggers etc.
    Please give me the query if someone has it.
    Thanks and Regards,
    Kapil Uppal

    Hi kapil wher do u stay......do u stay at UPPAL....grt,mine location is also uppal

  • Plz help, A select query for table giving foll o/p

    A table has a single column with following data
    Col1
    170
    10
    140
    520
    20
    60
    70
    The select query should return the data in the following format
    Col1 Col2 Col3 Col4
    170 3 1 0
    10 0 0 1
    140 2 2 0
    520 10 1 0
    20 0 1 0
    60 1 0 1
    70 1 1 0

    Using my awesome puzzle solving brain I note that Col2 = 50 Col3 = 20 Col4 = 10.
    But you should be telling US that.
    select col1, floor(col1/50) col2, floor(mod(col1,50)/20) col3, floor(mod(mod(col1,50),20)/10) col4
    from mytable.
    I win the internets!
    Edited by: Dave Hemming on Dec 19, 2008 11:35 AM

  • How to query for tables referenced to a certain table by a FK?

    Hello -
    I have a table called "SERVICE". i can't drop the table because it is referenced via a foreign key by other tables. What view(s) can I query to find the referenced tables?
    Thanks in advance!

    Does this query help?
    select /*+ parallel(4) */
    pk.table_name parent_table_name, pk.constraint_name pkey_constraint,
    fk.table_name child_table_name, fk.constraint_name fkey_constraint, fk.r_constraint_name
    from
    user_constraints pk,
    user_constraints fk
    where
    pk.constraint_name = fk.r_constraint_name
    and pk.constraint_type='P'
    and fk.constraint_type='R'

  • How to create query for tables with many to many relationship

    in my sql i'm unable to update the table using select clause...is there any way to update a table which is in many to many relationship.
    Ex:1st table student(student_id int primary key auto_increment, student_name varchar(30));
    2nd table contact (contact_id int primary key auto_increment, c_email varchar(40));
    3rd table student_contact(student_id int references student, contact_id int references contact);
    i would like to auto insert the both two columns in the student_contact while the student and the contact table being updated automatically.

    This is a JSP/JSTL forum, not a SQL forum. If you're using MySQL, better use their own forums at dev.mysql.com.
    I'll give some hints anyway: learn about SQL JOIN. In general there is good SQL documentation available at the website of the RDBMS manfacturer. Go check it out. There is also a nice SQL tutorial at w3schools.com. Good luck.

  • Unable to create Entity objects for tables in TimesTen database using ADF

    Hi,
    I am not able to create Entity and View objects for tables in TimesTen database using ADF. I have installed TimesTen client on my machine.
    I have created a database connection by using connection type as "Generic JDBC" and giving driver class and JDBC URL. I am attaching screen shot of the same.
    I am right clicking on Model project and selecting New option after that I am selecting ADF Business components and in it I am selecting Business components from tables and there I am querying for tables.I am getting list of tables and when I am trying to create a Entity object from the table after clicking finish Jdev is closing by itself giving an error.
    Can anyone please help me how to create Entity objects for tables using TimesTen as database.I might be missing some jars or the way I am creating connection might be wrong or any plugins required to connect to TimesTen.

    What is the actual error being given by Jdev? Are you sure that the JDBC connection is using the TimesTen JDBC driver JAR and not some other JDBC driver or the Generic JDBC/ODBC bridge?
    Is ADF even supported with TimesTen?
    Chris

  • CBO generating Parallel Query on tables of Degree 1

    In Oracle 9i release I have two tables which at one point in time were of degree 3. We have since changed these tables and their indexes back to degree 1 via ALTER TABLE ... PARALLEL (DEGREE 1) and ALTER INDEX ... PARALLEL (DEGREE 1). A query of DBA_TABLES and DBA_INDEXES verifies that the tables and their indexes are now degree 1. The database's OPTIMIZER_MODE is set to CHOOSE.
    For some reason the EXPLAIN PLAN of a SELECT statement joining these tables is showing a parallel query. The tables are listed with an "@:Q279919001" postfixes to the table name. I believe that indicates the CBO is going to do a parallel query.
    Why would the CBO choose a parallel query for tables which are degree 1?
    Mike

    try this
    ALTER TABLE TAB PARALLEL (DEGREE 1 INSTANCES 1);
    or
    ALTER TABLE TAB NOPARALLEL;
    Eugene Roytman

  • Query for Tracking the database

    Hai
    i am entering Some process in Client Application. Each process some records get updated in database tables.
    How can i fiind it? for example if i am updating engine menu of the application. engine table and some other tables are get updated. i dont have source code of application with me. how can i monitor that what are the tables get affected in the database.
    we have to work from database side.
    one thing i can do... write the query for table and count(*) after every process so that i can get which table get affected by identifying the row count.
    but i want only particular table get affected on particular process.
    Kindly give ur suggesiton
    S

    Well, you can connect as privileges user and issue:
    ALTER SYSTEM SET SQL_TRACE=TRUE;This will enable trace of every user session. So it is better if you are the only one using application and database. To find trace files location issue:
    SQL> select value from v$parameter where name = 'user_dump_dest';Trace files will have all SQL statements issued by a session. You can either read them raw (trace files are text files) or use Oracle supplied tkprof utility to format them.
    SY.
    P.S. Do not forget to turn off trace after you are done:
    ALTER SYSTEM SET SQL_TRACE=FALSE;

  • Need help with SQL Query (query for certain IDs in a table and then IDs not in result set)

    OK. This is hard to explain but that may be my problem in constructing the query.
    I have a table that has a list of jobs. The jobs information in this table, among other things, is a short description of the job itself (think "title" in phrase form), date, and ID.
    So I can query the table to get all the jobs for a particular grouping of IDs (the only ones I am interested in) that ran successfully for a given time period. But what I want are all the jobs that did not succeed (or therefore are not present in the table) for this group of jobs and for a certain date range. But these are not the only job id's in the table.
    To get the successful ones I do the following:
    SELECT id,short_desc FROM my_table where
                id IN('1230', '1231', '1232', '1239', '1244', '1245',
                '1246', '1247', '1248', '1272', '1280', '1281', '1282',
                '1283', '1284', '1285', '1286', '1249', '1250', '1251',
                '1252', '1253', '1255', '1233', '1234', '1235', '1236',
                '1237', '1238', '1256', '1257','1258', '1254', '1290','1310')
                AND the_date > = SYSDATE - 23/24
                AND to_char(the_date, 'DD-MON-YYYY') = TO_CHAR(CURRENT_DATE, 'DD-MON-YYYY')
    I have tried to use another AND clause with NOT IN and the group or NOT EXISTS but that doesn't work as there are other jobs captured in this table with id's of course. I am only concerned with these id's:
    IN('1230', '1231', '1232', '1239', '1244', '1245',
                '1246', '1247', '1248', '1272', '1280', '1281', '1282',
                '1283', '1284', '1285', '1286', '1249', '1250', '1251',
                '1252', '1253', '1255', '1233', '1234', '1235', '1236',
                '1237', '1238', '1256', '1257','1258', '1254', '1290','1310')
    Someone said to use a temp table. I don't think I have permission and I haven't tried as I want to do this in one query if possible.
    After thinking about this I am at a loss. I tried to do this in the front end but it just became too messy.

    You do not need a physical temp table. You need an in-line view:
    WITH list as (
                  SELECT '1230' id FROM DUAL UNION ALL
                  SELECT '1231' FROM DUAL UNION ALL
                  SELECT '1232' FROM DUAL UNION ALL
                  SELECT '1239' FROM DUAL UNION ALL
                  SELECT '1244' FROM DUAL UNION ALL
                  SELECT '1245' FROM DUAL UNION ALL
                  SELECT '1246' FROM DUAL UNION ALL
                  SELECT '1247' FROM DUAL UNION ALL
                  SELECT '1248' FROM DUAL UNION ALL
                  SELECT '1272' FROM DUAL UNION ALL
                  SELECT '1280' FROM DUAL UNION ALL
                  SELECT '1281' FROM DUAL UNION ALL
                  SELECT '1282' FROM DUAL UNION ALL
                  SELECT '1283' FROM DUAL UNION ALL
                  SELECT '1284' FROM DUAL UNION ALL
                  SELECT '1285' FROM DUAL UNION ALL
                  SELECT '1286' FROM DUAL UNION ALL
                  SELECT '1249' FROM DUAL UNION ALL
                  SELECT '1250' FROM DUAL UNION ALL
                  SELECT '1251' FROM DUAL UNION ALL
                  SELECT '1252' FROM DUAL UNION ALL
                  SELECT '1253' FROM DUAL UNION ALL
                  SELECT '1255' FROM DUAL UNION ALL
                  SELECT '1233' FROM DUAL UNION ALL
                  SELECT '1234' FROM DUAL UNION ALL
                  SELECT '1235' FROM DUAL UNION ALL
                  SELECT '1236' FROM DUAL UNION ALL
                  SELECT '1237' FROM DUAL UNION ALL
                  SELECT '1238' FROM DUAL UNION ALL
                  SELECT '1256' FROM DUAL UNION ALL
                  SELECT '1257' FROM DUAL UNION ALL
                  SELECT '1258' FROM DUAL UNION ALL
                  SELECT '1254' FROM DUAL UNION ALL
                  SELECT '1290' FROM DUAL UNION ALL
                  SELECT '1310' FROM DUAL
    SELECT  l.id,
            nvl(short_desc,'This job failed') short_desc
      FROM      my_table m
      WHERE RIGTH JOIN
                list
              ON (
                      m.id = l.id
                  AND
                      the_date > = SYSDATE - 23/24
                  AND
                      the_date < TRUNC(SYSDATE) + 1
    SY.

  • Oracle SQL query for getting specific special characters from a table

    Hi all,
    This is my table
    Table Name- Table1
    S.no    Name
    1          aaaaaaaa
    2          a1234sgjghb
    3          a@3$%jkhkjn
    4          abcd-dfghjik
    5          bbvxzckvbzxcv&^%#
    6          ashgweqfg/gfjwgefj////
    7          sdsaf$([]:'
    8          <-fdsjgbdfsg
    9           dfgfdgfd"uodf
    10         aaaa  bbbbz#$
    11         cccc dddd-/mnm
    The output has to be
    S.no    Name
    3          a@3$%jkhkjn
    5          bbvxzckvbzxcv&^%#
    7          sdsaf$([]:'
    8          <-fdsjgbdfsg
    10         aaaa  bbbbz#$
    It has to return "Name" column which is having special characters,whereas some special chars like -, / ," and space are acceptable.
    The Oracle query has to print columns having special characters excluding -,/," and space
    Can anyone help me to get a SQL query for the above.
    Thanks in advance.

    You can achieve it in multiple ways. Here are few.
    SQL> with t
      2  as
      3  (
      4  select 1 id, 'aaaaaaaa' name from dual union all
      5  select 2 id, 'a1234sgjghb' name from dual union all
      6  select 3 id, 'a@3$%jkhkjn' name from dual union all
      7  select 4 id, 'abcd-dfghjik' name from dual union all
      8  select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
      9  select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
    10  select 7 id, 'sdsaf$([]:''' name from dual union all
    11  select 8 id, '<-fdsjgbdfsg' name from dual union all
    12  select 9 id, 'dfgfdgfd"uodf' name from dual union all
    13  select 10 id, 'aaaa  bbbbz#$' name from dual union all
    14  select 11 id, 'cccc dddd-/mnm' name from dual
    15  )
    16  select *
    17    from t
    18   where regexp_like(translate(name,'a-/" ','a'), '[^[:alnum:]]');
            ID NAME
             3 a@3$%jkhkjn
             5 bbvxzckvbzxcv&^%#
             7 sdsaf$([]:'
             8 <-fdsjgbdfsg
            10 aaaa  bbbbz#$
    SQL> with t
      2  as
      3  (
      4  select 1 id, 'aaaaaaaa' name from dual union all
      5  select 2 id, 'a1234sgjghb' name from dual union all
      6  select 3 id, 'a@3$%jkhkjn' name from dual union all
      7  select 4 id, 'abcd-dfghjik' name from dual union all
      8  select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
      9  select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
    10  select 7 id, 'sdsaf$([]:''' name from dual union all
    11  select 8 id, '<-fdsjgbdfsg' name from dual union all
    12  select 9 id, 'dfgfdgfd"uodf' name from dual union all
    13  select 10 id, 'aaaa  bbbbz#$' name from dual union all
    14  select 11 id, 'cccc dddd-/mnm' name from dual
    15  )
    16  select *
    17    from t
    18   where translate
    19         (
    20            lower(translate(name,'a-/" ','a'))
    21          , '.0123456789abcdefghijklmnopqrstuvwxyz'
    22          , '.'
    23         ) is not null;
            ID NAME
             3 a@3$%jkhkjn
             5 bbvxzckvbzxcv&^%#
             7 sdsaf$([]:'
             8 <-fdsjgbdfsg
            10 aaaa  bbbbz#$
    SQL>

  • Select query for fetching from 3 tables.

    Can we have a single Select query for fetching same fields (kappl,kschl,vkorg,vtweg,spart,kunwe,datbi,knuma,datab,knumh)
    from 3 tables >> KOTE707,KOTE708 and KOTE709 into an internal table for a particular KUNNR?
    Regards,
    Shashank.

    Hi,
    If you have kunnr field in all the 3 tables then it is possible. use inner join as below
    PARAMETERS: p_cityfr TYPE spfli-cityfrom,
                p_cityto TYPE spfli-cityto.
    DATA: BEGIN OF wa,
             fldate TYPE sflight-fldate,
             carrname TYPE scarr-carrname,
             connid   TYPE spfli-connid,
           END OF wa.
    DATA itab LIKE SORTED TABLE OF wa
                   WITH UNIQUE KEY fldate carrname connid.
    SELECT c~carrname p~connid f~fldate
           INTO CORRESPONDING FIELDS OF TABLE itab
           FROM ( ( scarr AS c
             INNER JOIN spfli AS p ON p~carrid   = c~carrid
                                  AND p~cityfrom = p_cityfr
                                  AND p~cityto   = p_cityto )
             INNER JOIN sflight AS f ON f~carrid = p~carrid
                                    AND f~connid = p~connid ).
    LOOP AT itab INTO wa.
      WRITE: / wa-fldate, wa-carrname, wa-connid.
    ENDLOOP.
    <b>Reward Points if this helps,</b>
    Satish

  • Query for how to display unique rows in a table

    Can i have a query for displaying unique rows in a table.

    use d query
    select distinct col1,col2... from table ;

  • Trouble writing Query for Pivoting data from a table

    I am having a little trouble writing a query for converting the below table data into a pivot data. I am trying to write a query for which if I give a single valid report_week date as input it should give me the data for that week and also provide two extra columns, one which gives the data of last week for the same countries and the second column which gives the difference of numbers in both the columns(i.e. COUNT - COUNT_LAST_WEEK).
    REPORT_WEEK     DIVISION     COUNT
    9/26/2009     country1     81
    9/26/2009     country2     97
    9/26/2009     country3     12
    9/26/2009     country4     26
    9/26/2009     country5     101
    10/3/2009     country1     85
    10/3/2009     country2     98
    10/3/2009     country3     10
    10/3/2009     country4     24
    10/3/2009     country5     101
    10/10/2009     country1     84
    10/10/2009     country2     98
    10/10/2009     country3     10
    10/10/2009     country4     25
    10/10/2009     country5     102
    For example, if I give input as 10/10/2009, the output should be as give below.
    REPORT_WEEK     DIVISION     COUNT     COUNT_LAST_WEEK     DIFFERENCE
    10/10/2009     country1     84     85     -1
    10/10/2009     country2     98     98     0
    10/10/2009     country3     10     10     0
    10/10/2009     country4     25     24     1
    10/10/2009     country5     102     101     1
    For example, if I give input as 10/3/2009, the output should be as give below.
    REPORT_WEEK     DIVISION     COUNT     COUNT_LAST_WEEK     DIFFERENCE
    10/3/2009     country1     85     81     4
    10/3/2009     country2     98     97     1
    10/3/2009     country3     10     12     -2
    10/3/2009     country4     24     26     -2
    10/3/2009     country5     101     101     0
    Can anyone please shed some light on Query building for the above scenarios.
    Thank you
    SKP
    Edited by: user11343284 on Oct 10, 2009 7:53 AM
    Edited by: user11343284 on Oct 10, 2009 8:28 AM

    I assume there is no gap in report weeks. If so:
    SQL> variable report_week varchar2(10)
    SQL> exec :report_week := '10/10/2009'
    PL/SQL procedure successfully completed.
    with t as (
               select to_date('9/26/2009','mm/dd/yyyy') report_week,'country1' division,81 cnt from dual union all
               select to_date('9/26/2009','mm/dd/yyyy'),'country2',97 from dual union all
               select to_date('9/26/2009','mm/dd/yyyy'),'country3',12 from dual union all
               select to_date('9/26/2009','mm/dd/yyyy'),'country4',26 from dual union all
               select to_date('9/26/2009','mm/dd/yyyy'),'country5',101 from dual union all
               select to_date('10/3/2009','mm/dd/yyyy'),'country1',85 from dual union all
               select to_date('10/3/2009','mm/dd/yyyy'),'country2',98 from dual union all
               select to_date('10/3/2009','mm/dd/yyyy'),'country3',10 from dual union all
               select to_date('10/3/2009','mm/dd/yyyy'),'country4',24 from dual union all
               select to_date('10/3/2009','mm/dd/yyyy'),'country5',101 from dual union all
               select to_date('10/10/2009','mm/dd/yyyy'),'country1',84 from dual union all
               select to_date('10/10/2009','mm/dd/yyyy'),'country2',98 from dual union all
               select to_date('10/10/2009','mm/dd/yyyy'),'country3',10 from dual union all
               select to_date('10/10/2009','mm/dd/yyyy'),'country4',25 from dual union all
               select to_date('10/10/2009','mm/dd/yyyy'),'country5',102 from dual
    select  max(report_week) report_week,
            division,
            max(cnt) keep(dense_rank last order by report_week) cnt_this_week,
            max(cnt) keep(dense_rank first order by report_week) cnt_last_week,
            max(cnt) keep(dense_rank last order by report_week) - max(cnt) keep(dense_rank first order by report_week) difference
      from  t
      where report_week in (to_date(:report_week,'mm/dd/yyyy'),to_date(:report_week,'mm/dd/yyyy') - 7)
      group by division
      order by division
    REPORT_WE DIVISION CNT_THIS_WEEK CNT_LAST_WEEK DIFFERENCE
    10-OCT-09 country1            84            85         -1
    10-OCT-09 country2            98            98          0
    10-OCT-09 country3            10            10          0
    10-OCT-09 country4            25            24          1
    10-OCT-09 country5           102           101          1
    SQL> exec :report_week := '10/3/2009'
    PL/SQL procedure successfully completed.
    SQL> /
    REPORT_WE DIVISION CNT_THIS_WEEK CNT_LAST_WEEK DIFFERENCE
    03-OCT-09 country1            85            81          4
    03-OCT-09 country2            98            97          1
    03-OCT-09 country3            10            12         -2
    03-OCT-09 country4            24            26         -2
    03-OCT-09 country5           101           101          0
    SQL> SY.

  • Query a table according to SYSTIMESTAMP  for records within an interval

    Hello ,
    I am trying to query a table based on the systimestamp and taking two timestamp as intervals.Following is the query:
    select * FROM MY_TBL where to_char(SYSTIMESTAMP,'YYYY-MM-DD HH24:MI:SS')
    BETWEEN (to_char(SYSTIMESTAMP - INTERVAL '40' hour, 'yyyy-mm-dd HH24:MI:SS'))
    AND (to_char(SYSTIMESTAMP - INTERVAL '16' hour, 'yyyy-mm-dd HH24:MI:SS'));
    I am not getting any results.(no rows selected)
    So i tried:
    SELECT * FROM MY_TBL AS OF TIMESTAMP
    to_date(to_char(SYSTIMESTAMP - INTERVAL '40' hour, 'yyyy-mm-dd HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS')
    - to_date(to_char(SYSTIMESTAMP - INTERVAL '16' hour, 'yyyy-mm-dd HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS');
    ERROR at line 3:
    ORA-00932: inconsistent datatypes: expected TIMESTAMP got DATE JULIAN
    Since TIMESTAMP is in a different format.I may be getting this error.How do i cast TIMESTAMP in the above query to map to the intervals.
    Please let me know how to approach this issue.
    Thanks in Advance,
    Santosh

    Thanks for the quick and prompt replies....
    To provide a quick background.I am providing a daily report to my customer which is based on column (DATE type) in the table.But the records were inconsistent.Hence it was agreed that we get the report based on systime stamp.
    Range is : between day-before-yesterday midnight(START_TIME) and yesterday midnight(END_TIME).A perl script runs the report at midnight 2 AM as cron .So i figure the interval can be :
    (SYSTIMESTAMP - INTERVAL '40' hour) - It is 12 AM day before-yesterday-night if run at 2 AM - Interval 1
    --------------------------------------------------------BETWEEN----------------------------------------------------------------------------
    (SYSTIMESTAMP - INTERVAL '16' hour) - It is 12 AM day yesterday-night if run at 2 AM - Interval 2
    SQL> select to_timestamp(to_char(SYSTIMESTAMP - INTERVAL '40' hour, 'yyyy-mm-dd HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS')START_TIME from dual;
    START_TIME
    08-JUN-09 06.43.59.000000000 PM
    SQL> select to_timestamp(to_char(SYSTIMESTAMP - INTERVAL '16' hour, 'yyyy-mm-dd HH24:MI:SS'),'YYYY-MM-DD HH24:MI:SS') END_TIME from dual
    2 ;
    END_TIME
    09-JUN-09 06.44.46.000000000 PM
    How do i get the records for these two intervals.
    Thankyou..
    -Santosh

Maybe you are looking for