Query with dates

hi every body
i want to select date from today_date(column) from patients(table)
select today_date from patients where today_date = 17||''||12||80 ;
the problem is that i tried this in sql (example) 17||''||12||80 and it worked
but
when i changed the (12) to (02) refer to (february not december) there was an error
( literal does not match format string) -- error
why that happened
thanks a lot

Hi,
semsem wrote:
i am sorry for u all but non of u got me
i said that i did that in sql because we are in sql forum
but clearly i need that in forms builder , if u know about that It may be clear to you, but if you don't say you're using Forms Builder, why would anyone guess that? If you want help with your problem, then say what your problem is.
i have 3 list items in my form (1,2,3)
1- hold the value for days
2- the value for months
3- for years
and i wanna choose the date from the database from today_date(column) from patients(table) where
today_date = :list1||:list2||list3 In case it's not clear from the earlier replies, the different data types are not all the same. It may matter what kind of data type you're using in any given expression.
What are the data types of :list1, :list2 and :lsit3?
If they are all strings (e.g. VARCHAR2 or CHAR), then this example from my previous message applies:
Frank Kulash wrote:
WHERE      today_date = TO_DATE ( '17' || '02' || '80'
                         , 'DDMMRR'
                    ) but instead of the string literals '17', '02' amd '80', use your variables :lsit1, :lsit2 and :list3. You many want to do this:
WHERE      today_date = TO_DATE ( :list1 || :list2 || :list3
                         , 'DDMMRR'           -- 2-digt years are a very bad idea
                    ) assuming that
:list1 represents the day, :list2 represents the month, and :lsit3 represents the year. A lot of folks would use variable names that mean something, like
:day, :month and :year, or
:target_day, :target_month and :target_year.
If the data type of all 3 variables is NUMBER, then this example from my previous message appplies:
WHERE      today_date = TO_DATE ( TO_CHAR (17, 'FM00') ||
                           TO_CHAR (02, 'FM00') ||
                      TO_CHAR (80, 'FM00')
                         , 'DDMMRR'
                    )Again, you have to use your variables in place of the literals, so you'd do something like:
WHERE      today_date = TO_DATE ( TO_CHAR (:list1, 'FM00') ||
                           TO_CHAR (:list2, 'FM00') ||
                      TO_CHAR (:list3, 'FM00')
                         , 'DDMMRR'          -- 2-digit years are simply asking for trouble
                    )

Similar Messages

  • How to compare result from sql query with data writen in html input tag?

    how to compare result
    from sql query with data
    writen in html input tag?
    I need to compare
    user and password in html form
    with all user and password in database
    how to do this?
    or put the resulr from sql query
    in array
    please help me?

    Hi dejani
    first get the user name and password enter by the user
    using
    String sUsername=request.getParameter("name of the textfield");
    String sPassword=request.getParameter("name of the textfield");
    after executeQuery() statement
    int exist=0;
    while(rs.next())
    String sUserId= rs.getString("username");
    String sPass_wd= rs.getString("password");
    if(sUserId.equals(sUsername) && sPass_wd.equals(sPassword))
    exist=1;
    if(exist==1)
    out.println("user exist");
    else
    out.println("not exist");

  • Query with date in where clause

    hi,
    i have build a view with join conditions from 8 tables. the data from this view is more then 100,000
    when i run the query with different clause its work with some seconds. but when i put date column in where cluase it sleeps.
    eg..
    where unit_id = 4 and t_id = 's09' and vb like '%amb%'
    works fine.
    where unit_id = 4 and t_id = 's09' and vb like '%amb%' and date between dt1 and dt2
    now sleep
    please ......give me some suggestions

    hi i have done the explain plan
    the result is
    Operation Object
    SELECT STATEMENT ()
    NESTED LOOPS ()
    NESTED LOOPS ()
    HASH JOIN ()
    HASH JOIN ()
    TABLE ACCESS (FULL) PR_PO_MST
    TABLE ACCESS (FULL) PR_SUPPLIER
    TABLE ACCESS (FULL) PR_PO_DTL
    TABLE ACCESS (BY INDEX ROWID) INDENT_MST
    INDEX (RANGE SCAN) ST_IND_MST_IDX
    TABLE ACCESS (BY INDEX ROWID) ST_ITEM
    Operation Object
    INDEX (UNIQUE SCAN) PK_ST_ITEM
    now wot do do????

  • *Urgent* Query with dates

    Hi Gurus,
    I am having problem in developing such a query which has calculations with dates. The problem is:
    I have
    base date for example 26-feb-2006
    statring day: 4
    interval: 5
    input date: 15-mar-2006
    Now the problem is I want to get the results from the query which will start 26-feb-2006+4 which is 02-mar-2006 and calculate the interval which is 5 days from '02-mar-2006' and run it every 5 (interval) days
    02-mar-2006
    07-mar-2006
    12-mar-2006
    I hope I have cleared everything.
    Please let me know as soon as possible.
    Thanks in advance.
    Aqil

    Where is the base_date coming from?
    declare
    v_jobno number;
    dbms_job.submit(v_jobno, 'SCHEMA_NAME.sp_my_proc();',
    -- first time running I schedule for 11 pm staring in 4 days
                              trunc(sysdate+4)+23/24,
    -- here the interval
                              'trunc(sysdate+5)+23/24' );
    end;

  • Doubt querying with dates

    Hi all,i have a doubt querying an sql statement which involves date.
      1  SELECT rsh.shipment_num "File#"
      2        ,mmt.transaction_date "Transaction Date"
      3  FROM rcv_shipment_headers rsh,
      4       ap_suppliers aps,
      5    po_headers_all pha,
      6    po_lines_all pla,
      7    mtl_system_items_kfv msi,
      8    rcv_shipment_lines rsl,
      9    rcv_transactions rcv,
    10    mtl_material_transactions mmt,
    11    mtl_transaction_types mtt
    12  WHERE rsh.vendor_id = aps.vendor_id
    13  AND pha.po_header_id = pla.po_header_id
    14  AND pla.item_id = msi.inventory_item_id
    15  AND pha.po_header_id = rsl.po_header_id
    16  and pla.po_line_id = rsl.po_line_id
    17  AND rsl.shipment_header_id = rsh.shipment_header_id
    18  AND rsl.item_id = msi.inventory_item_id
    19  AND rsl.to_organization_id = msi.organization_id
    20  AND rcv.shipment_header_id = rsh.shipment_header_id
    21  AND rcv.organization_id = msi.organization_id
    22  AND rcv.po_header_id = pha.po_header_id
    23  AND rcv.po_line_id = pla.po_line_id
    24  --and pla.org_id = msi.organization_id
    25  AND rsh.SHIPMENT_NUM = 'AP1005'
    26  --AND mmt.transaction_date = TO_CHAR(TO_DATE('14-SEP-2012','DD-MON-YYYY'))
    27  AND rcv.transaction_type = 'DELIVER'
    28  AND rcv.source_document_code = 'PO'
    29  --AND rcv.subinventory = 'Vessel'
    30  AND mmt.rcv_transaction_id = rcv.transaction_id
    31  AND mmt.transaction_type_id = mtt.transaction_type_id
    32* AND rcv.organization_id = 81
    SQL> /
    File#                          Transacti
    AP1005                         14-SEP-12
    AP1005                         14-SEP-12Now passing date
      1  SELECT rsh.shipment_num "File#"
      2        ,mmt.transaction_date "Transaction Date"
      3  FROM rcv_shipment_headers rsh,
      4       ap_suppliers aps,
      5    po_headers_all pha,
      6    po_lines_all pla,
      7    mtl_system_items_kfv msi,
      8    rcv_shipment_lines rsl,
      9    rcv_transactions rcv,
    10    mtl_material_transactions mmt,
    11    mtl_transaction_types mtt
    12  WHERE rsh.vendor_id = aps.vendor_id
    13  AND pha.po_header_id = pla.po_header_id
    14  AND pla.item_id = msi.inventory_item_id
    15  AND pha.po_header_id = rsl.po_header_id
    16  and pla.po_line_id = rsl.po_line_id
    17  AND rsl.shipment_header_id = rsh.shipment_header_id
    18  AND rsl.item_id = msi.inventory_item_id
    19  AND rsl.to_organization_id = msi.organization_id
    20  AND rcv.shipment_header_id = rsh.shipment_header_id
    21  AND rcv.organization_id = msi.organization_id
    22  AND rcv.po_header_id = pha.po_header_id
    23  AND rcv.po_line_id = pla.po_line_id
    24  --and pla.org_id = msi.organization_id
    25  --AND rsh.SHIPMENT_NUM = 'AP1005'
    26  AND mmt.transaction_date = TO_CHAR(TO_DATE('14-SEP-2012','DD-MON-YYYY'))
    27  AND rcv.transaction_type = 'DELIVER'
    28  AND rcv.source_document_code = 'PO'
    29  --AND rcv.subinventory = 'Vessel'
    30  AND mmt.rcv_transaction_id = rcv.transaction_id
    31  AND mmt.transaction_type_id = mtt.transaction_type_id
    32* AND rcv.organization_id = 81
    SQL> /
    no rows selectedCan anyone pls suggest me where i am doing wrong.
    Any help is appreciated,
    Thanks in advance

    You have already got your answer.
    >
    yes works out,thanks very much.May i know the reason why it didn't worked out earlier?
    Thanks
    >
    Hope, the below example will make things more clear to you.
    SQL> CREATE TABLE m003 AS
      2    (SELECT 1                                                       id,
      3            To_date('14/09/2012 23:00:00', 'dd/mm/yyyy hh24:mi:ss') dt
      4     FROM   dual
      5     UNION ALL
      6     SELECT 2,
      7            To_date('14/09/2012 00:00:00', 'dd/mm/yyyy hh24:mi:ss')
      8     FROM   dual
      9     UNION ALL
    10     SELECT 3,
    11            To_date('14/09/2012 01:00:00', 'dd/mm/yyyy hh24:mi:ss')
    12     FROM   dual
    13     UNION ALL
    14     SELECT 4,
    15            To_date('02/03/2012 23:00:00', 'dd/mm/yyyy hh24:mi:ss')
    16     FROM   dual);
    Table created.
    SQL> select * from m003;
            ID DT
             1 14-SEP-12
             2 14-SEP-12
             3 14-SEP-12
             4 02-MAR-12
    SQL> SELECT *
      2  FROM   m003
      3  WHERE  dt = To_char(To_date('14-SEP-2012', 'DD-MON-YYYY'));
            ID DT                                                                  
             2 14-SEP-12   Here, 14-SEP-2012 is a string. You are converting a string to date to compare with a column data which is a date. It does not make sense to convert to string again!
    SQL> select to_char(TO_DATE('14-SEP-2012','DD-MON-YYYY'),'DD-MON-YYYY HH24:MI:SS
    ')  from dual;
    TO_CHAR(TO_DATE('14-
    14-SEP-2012 00:00:00As you can see, TO_DATE('14-SEP-2012','DD-MON-YYYY') returns 14-SEP-2012 00:00:00.
    SQL> select * from m003
      2  where dt= TO_DATE('14-SEP-2012','DD-MON-YYYY');
            ID DT                                                                  
             2 14-SEP-12   In the above sql, it searches for the data that matches with date 14-SEP-2012 00:00:00 and hence 1 row.
    if your objective is to get the records where date is 14-SEP-2012 irrespective of the time associated with it,then write..
    SQL> select * from m003
      2  where dt >= TO_DATE('14-SEP-2012','DD-MON-YYYY')
      3  and dt < TO_DATE('14-SEP-2012','DD-MON-YYYY')+1
      4  ;
            ID DT                                                                  
             1 14-SEP-12                                                           
             2 14-SEP-12                                                           
             3 14-SEP-12     Now, what is the problem in below sql
    SQL> select * from m003
      2  where trunc(dt)= TO_DATE('14-SEP-2012','DD-MON-YYYY');
            ID DT                                                                  
             1 14-SEP-12                                                           
             2 14-SEP-12                                                           
             3 14-SEP-12   The SQL above will return same result as above BUT..
    In this case you are truncating the time for all the rows (ie time associated with the date will be 00:00:00) applying function trunc() which would be a bit slower. Moreover,
    if there is any index on this column then use of function on the column will ignore the index (if it is not a function based index).
    Hope it helps.
    Regards
    Biju

  • GL Trial Balance Report Query with date Effectivity

    We have a requirement to show the GL Trial Balance report with Effective dates as Parameters.
    Current Analysis:
    The Journals get updated with corresponding CCID in GL_BALANCES table when the Journal is posted. GL_BALANCE is SOB specific, if the SOB has month as period then the balances in GL_BALANCES would get updated against the month(period).
    To overcome the period problem, we explored the option of using a View based on GL_JE_HEADERS and GL_JE_LINES for 'Posted' Journal Batches of a SOB. We are checking whether the GL_JE_HEADERS.default_effective_date lies between the :p_from_date and :p_to_date which is sent to the Report as a parameter. The above idea does not return expected data when the custom Trial Balance Report is run.
    Following is the Query we have written for it:
    SELECT cc.segment4 ACCOUNT, bal.code_combination_id,
    bal.begin_balance_dr
    + SUM (NVL (gljel.accounted_dr, 0)) opening_bal_dr,
    bal.begin_balance_cr
    + SUM (NVL (gljel.accounted_cr, 0)) opening_bal_cr,
    ffv.description,
    (SELECT SUM (NVL (gljel.accounted_dr, 0))
    FROM gl_je_headers gljeh,
    gl_je_lines gljel,
    gl_code_combinations gcc
    WHERE gljeh.default_effective_date BETWEEN :p_from_date
    AND :p_to_date
    AND gljeh.je_header_id = gljel.je_header_id
    AND gljel.code_combination_id = gcc.code_combination_id
    AND gljel.period_name = gljeh.period_name
    AND gljel.set_of_books_id = :p_set_of_books_id
    AND gljeh.status = 'P'
    AND gljel.status = 'P'
    AND gljeh.actual_flag = 'A'
    --AND gljel.code_combination_id =
    -- bal.code_combination_id
    AND gcc.segment4 = cc.segment4
    GROUP BY gcc.segment4) c_dr,
    (SELECT SUM (NVL (gljel.accounted_cr, 0))
    FROM gl_je_headers gljeh,
    gl_je_lines gljel,
    gl_code_combinations gcc
    WHERE gljeh.default_effective_date BETWEEN :p_from_date
    AND :p_to_date
    AND gljeh.je_header_id = gljel.je_header_id
    AND gljel.period_name = gljeh.period_name
    AND gljel.code_combination_id = gcc.code_combination_id
    AND gljel.set_of_books_id = :p_set_of_books_id
    AND gljeh.status = 'P'
    AND gljel.status = 'P'
    AND gljeh.actual_flag = 'A'
    AND gcc.segment4 = cc.segment4
    GROUP BY gcc.segment4) c_cr
    FROM gl_period_statuses per,
    gl_code_combinations cc,
    gl_balances bal,
    gl_je_headers gljeh,
    gl_je_lines gljel,
    fnd_flex_values_vl ffv,
    fnd_flex_value_sets ffvs
    WHERE cc.chart_of_accounts_id = :p_chart_of_accts_id
    AND bal.currency_code = :p_currency
    AND bal.actual_flag = 'A'
    AND bal.period_name = per.period_name
    AND cc.template_id IS NULL
    AND cc.code_combination_id = bal.code_combination_id
    AND per.set_of_books_id = :p_set_of_books_id
    AND per.application_id = 101
    AND :p_from_date BETWEEN per.start_date AND per.end_date
    AND gljeh.period_name = per.period_name
    AND gljeh.default_effective_date <= :p_from_date
    AND gljeh.je_header_id = gljel.je_header_id
    AND gljel.period_name = gljeh.period_name
    AND gljel.set_of_books_id = :p_set_of_books_id
    AND ffv.flex_value_set_id = ffvs.flex_value_set_id
    AND ffvs.flex_value_set_name = 'JSWEL_ACCOUNT'
    AND gljeh.status = 'P'
    AND gljel.status = 'P'
    AND cc.summary_flag = ffv.summary_flag
    AND cc.segment4 = ffv.flex_value
    AND gljeh.actual_flag = 'A'
    AND gljel.code_combination_id = bal.code_combination_id
    GROUP BY bal.begin_balance_dr,
    bal.begin_balance_cr,
    cc.segment4,
    ffv.description,
    bal.code_combination_id
    The problem is that not all expected columns are being queried. Kindly advise as appropriate.
    Note: I have also posted this thread on the Financials forum. Posting here to present the query to a larger audience with the expectation that my query would be answered.
    Thanks & Regards
    Sumit

    suggest to create customize TB report.

  • Query with date variable selection

    Greetings,
    I am having problems with a SQL Query and wondering if someone could help me out.  I have the following query and want to specify a WHERE clause and have the user select the date range they want to work with.  If I specify a date the query runs fine.  If I enter in the [%0] I get an error message saying: "incorrect syntax near '<'.
    Any help would be appreciated.
    select
    'W' as prefix,
    empid as [Employee Number] ,
    U_PayrollCat as [Payroll Category Code],
    '' as [Cost Center Code],
    ContractID as     [Job Center Code],
    Segment_0 + isnull( ActSep + Segment_1, '') + isnull(ActSep  + Segment_2, '') 
                          + isnull(ActSep + Segment_3, '') + isnull(ActSep + Segment_4, '') 
                          + isnull( ActSep  + Segment_5, '') + isnull(ActSep + Segment_6, '')
                          + isnull(ActSep + Segment_7, '') + isnull(ActSep  + Segment_8, '')
                          + isnull( ActSep + Segment_9, '') as [GL Account Code],
    quantity as Units,
    U_NBS_ITEMCOST/quantity as Rate,
    U_NBS_ITEMCOST as Amount,
    oclg.notes as Comments,
    oclg.recontact as [WorkDate],
    '' as[Department code]
    from
    oclg inner join
    dln1 on dln1.docentry =oclg.docentry inner join 
    odln on odln.docentry = dln1.docentry inner join
    ohem on ohem.userid = oclg.attenduser
    inner join oitm on oitm.itemcode = dln1.itemcode
    inner join oscl on oscl.callid = odln.U_NBS_S1Link
    inner join OACT on  OACT.AcctCode = dln1.cogsAcct
    inner join oadm on 1=1
    WHERE
    oclg.recontact >= [%0] AND oclg.recontact <= [%1]

    Gordon,
    That worked with a few modifications.  Removed comma on line before FROM clause and my UDF for Payroll Category is on my OITM table.  Complete Query looked like this:
    SELECT 'W' as prefix, t3.empid as 'Employee Number',
    t4.U_PayCat as 'Payroll Category Code',
    t5.ContractID as 'Job Center Code',
    t6.Segment_0 + isnull( ActSep + t6.Segment_1, '') + isnull(ActSep + t6.Segment_2, '')
    + isnull(ActSep + t6.Segment_3, '') + isnull(ActSep + t6.Segment_4, '')
    + isnull( ActSep + t6.Segment_5, '') + isnull(ActSep + t6.Segment_6, '')
    + isnull(ActSep + t6.Segment_7, '') + isnull(ActSep + t6.Segment_8, '')
    + isnull( ActSep + t6.Segment_9, '') as 'GL Account Code',
    t1.quantity as Units,
    t1.U_NBS_ITEMCOST/t1.quantity as Rate,
    t1.U_NBS_ITEMCOST as Amount,
    t0.notes as Comments,
    t0.recontact as WorkDate
    from dbo.oclg t0
    inner join dbo.dln1 t1 on t1.docentry =t0.docentry
    inner join dbo.odln t2 on t2.docentry = t1.docentry
    inner join dbo.ohem t3 on t3.userid = t0.attenduser
    inner join dbo.oitm t4 on t4.itemcode = t1.itemcode
    inner join dbo.oscl t5 on t5.callid = t2.U_NBS_S1Link
    inner join dbo.OACT t6 on T6.AcctCode = t1.cogsAcct
    inner join dbo.oadm t7 on 1=1
    WHERE t0.recontact >= '[%0]' AND t0.recontact <= '[%1]'
    Thanks for the help,
    Aaron

  • Oracle OCI: Problem in Query with Date field

    Client compiled with OCI: 10.2.0.4.0
    Server: Oracle9i Enterprise Edition Release 9.2.0.4.0
    The problematic query is:
    SELECT CODIGO FROM LOG WHERE TEL = :telnumber AND DATE_PROC = '05-JUL-08'Table description:
    SQL>describe LOG;
    TEL NOT NULL VARCHAR2(15)
    CODIGO NOT NULL VARCHAR2(20)
    DATE_PROC NOT NULL DATEAs simple as it might look, when executed directly on the server with SQLPlus, it returns a result, but when executed from the app that uses OCI, this query returns OCI_NO_DATA always. In the beginning, the date value was also a placeholder, but I found out that even giving a literal like '05-JUL-08' didn't work. I have tried the following:
    <ul>
    <li>I've tried the basics: querying the DB from the client does work. It's this one that gives me trouble</li>
    <li>The query: SELECT CODIGO FROM LOG WHERE TEL = :telnumber does work</li>
    <li>Executing: ALTER SESSION SET NLS_DATE_FORMAT="DD-MM-YYYY"; before the query in both the server and the client. Same result: server returns data, client OCI_NO_DATA</li>
    <li>Tried changing DATE_PROC format, combining this with the use of TO_DATE(). Same result.</li>
    <li>Searched, searched, searched. No answer</li>
    </ul>
    I'm a bit desperate to find an answer, would appreciate any help and can provide as many further details as needed. Thanks.
    Edited by: user12455729 on Jan 15, 2010 5:59 AM. -Formatting-

    Hi,
    I've recreated your table and populated with your data.
    I've run your select using OCILIB on a 10gR2 (client and server) and the codes runs fine and give expected results.
    So the problem must resides in your code.... (i don't think it can be a OCI bug)
    Here is the ocilib code :
    #include "ocilib.h"
    int main(void)
        OCI_Connection *cn;
        OCI_Statement *st;
        OCI_Resultset *rs;
        char msisdn[100] = "11223344";
        char datetime[100] = "";
        if (!OCI_Initialize(err_handler, NULL, OCI_ENV_DEFAULT))
            return EXIT_FAILURE;
        cn = OCI_ConnectionCreate("db", "usr", "pwd", OCI_SESSION_DEFAULT);
        st = OCI_StatementCreate(cn);
        OCI_Prepare(st, "SELECT "
                        "  CODIGO_BANCO "
                        "FROM "
                        "  VTA_LOG "
                        "WHERE "
                        "  TELEFONO = :msisdn AND "
                        "  FECHA_PROCESO = TO_DATE(:datetime, 'YYYYMMDDHH24MISS')");
        OCI_BindString(st, "msisdn", msisdn, sizeof(msisdn)-1);
        OCI_BindString(st, "datetime", datetime, sizeof(datetime)-1);
        strcpy(datetime, "20080705162918");
        OCI_Execute(st); 
        rs = OCI_GetResultset(st);
        OCI_FetchNext(rs);
        printf("%s\n", OCI_GetString(rs, 1));
        strcpy(datetime, "20080705062918");
        OCI_Execute(st); 
        rs = OCI_GetResultset(st);
        OCI_FetchNext(rs);
        printf("%s\n", OCI_GetString(rs, 1));
        OCI_Cleanup();
        return EXIT_SUCCESS;
    }Output is :
    BancoOne
    BancoTwoi recreated your data with
    create table VTA_LOG
         TELEFONO          VARCHAR2(15) NOT NULL ,
         CODIGO_BANCO     VARCHAR2(20) NOT NULL ,
         FECHA_PROCESO     DATE NOT NULL
    insert into VTA_LOG values ('11223344', 'BancoOne',  to_date('20080705162918', 'YYYYMMDDHH24MISS'));
    insert into VTA_LOG values ('11223344', 'BancoTwo', to_date('20080705062918', 'YYYYMMDDHH24MISS'));
    commit;Regards,
    Vincent

  • Creating a Query with Data from 4 Tables.

    Hey guys. I'm having a small problem figuring out the best way for me to handle this query.
    I'm trying to make a query which outputs the amount of appointments a GP has furfilled, and the total amount allowed.
    I have 4 tables, for each I'm just gonna list the relevent columns:
    Appointment: ID, Patient_ID.
    Patient: ID, GP_ID.
    GP: ID, Trust_ID.
    Trust: ID, Quota.
    Appointment table has 400 entries (2 per patient atm).
    Patient table has 200 entries.
    GP Table has 30 entries (GP's can be assigned to more than one person) .
    Trust table has 6 entries.
    What I need to do is, look at the appointment table and get the number of times each patient has an appointment.
    Go through the patient table, and find out which GP the patient in the appointment belongs to.
    Add each occurance to the correct GP.
    Find out which Trust each GP belongs to, and add the total for each GP to the correct Trust.
    Check the quota in the Trust table, to see if the total is more than the allowed.
    I can't seem to think of an easy or simple way for me to do this. Can anyone help please? Many thanks.

    Hi,
    That sounds like a job for JOIN.
    To check the quotas against the total, use the SUM function; either the aggregate SUM or the analytic SUM, depending on your requirements.
    Sorry this answer is so vague, but that's the bes I can do with the information provided so far.
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved. In this case, between 2 and 10 rows of data per table should be enough to show what you need to do.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Always say which version of Oracle you're using.

  • Table joining query with dates

    Hello,
    I have two tables, one containing a list of pupils, their class start date and their class end dates. The second table contains the address (postcode) history of the pupil. I need to bring these two tables together into one query to show all the classes from the 'pupils' table and add in the most recent postcode of the address prior to the start date of the clasS from the 'addresses' table.  I.e. to show where the pupil lived when they started the class.
    Could anyone show me how to do this please? I've provided a 'desired' table to show what I need the results to look like.
    I hope this is clear, please ask if it isn't - I'm sure this should be simple! But I can't get my head around it. I'm using Oracle 9i and SQL Developer.
    Thanks :)
    select pupils.* from
    (select 'A227' as pupil_id, to_date('21/04/2010','dd/mm/rrrr') class_start, to_date('21/09/2010','dd/mm/rrrr') class_end from dual union all
    select 'A227' as pupil_id, to_date('08/08/2011','dd/mm/rrrr'), to_date('26/10/2011','dd/mm/rrrr') from dual ) pupils
    select addresses.* from
    (select 'A227' as pupil_id, to_date('20/04/2010','dd/mm/rrrr') address_start, null address_end, 'TW1 XVT' as postcode from dual union all
    select 'A227' as pupil_id, to_date('03/08/2011','dd/mm/rrrr'), to_date('31/10/2011','dd/mm/rrrr'), 'TW3 ZE3' as postcode from dual union all
    select 'A227' as pupil_id, to_date('01/11/2011','dd/mm/rrrr'), null, 'n23 4ty' as postcode from dual) addresses
    select desired.* from
    (select 'A227' as pupil_id, to_date('21/04/2010','dd/mm/rrrr') class_start, to_date('21/09/2010','dd/mm/rrrr') class_end, to_date('20/04/2011','dd/mm/rrrr') as address_start, 'TW1 XVT' as postcode from dual union all
    select 'A227' as pupil_id, to_date('08/08/2011','dd/mm/rrrr') class_start, to_date('26/10/2011','dd/mm/rrrr') class_end, to_date('03/08/2011','dd/mm/rrrr') as  address_start, 'TW3 ZE3' as postcode from dual) desired
     

    Hi,
    That's an example of a Top-N Query , and here's one way to do it:
    WITH     got_r_num     AS
         SELECT     p.*
         ,     a.address_start
         ,     a.postcode
         ,     ROW_NUMBER () OVER ( PARTITION BY  p.pupil_id
                                   ,                    p.class_start
                                   ORDER BY          a.address_start     DESC
                           )         AS r_num
         FROM     pupils        p
         JOIN     addresses  a  ON   p.pupil_id        = a.pupil_id
                         AND  p.class_start  >= a.address_start
    SELECT     pupil_id, class_start, class_end, address_start, postcode
    FROM     got_r_num
    WHERE     r_num     = 1
    ;As you can see, the sib-query pairs each pupil and class with all the earlier addresses, and then numbers the addresses such that the latest address_start gets the lowest r_num (that is, 1, since ROW_NUMBER always starts with 1). The main query displays only the most recent address (the one with r_num = 1) for each pupil and class.
    Does addresses.address_end plays any role in this problem? For example, would it matter if the most recent address for a given pupil and class had expired before the class started? That is, if we change the middle of address to:
    select  'A227'          as pupil_id
    ,      to_date ('03/08/2011', 'dd/mm/rrrr')
    ,      to_date ('07/08/2011', 'dd/mm/rrrr')     -- Not 31/10/2011
    ,      'TW3 ZE3'      as postcode
    from      dual would it still count as the last address before the class that started on 08/08/2011?
    Edited by: Frank Kulash on Nov 1, 2011 11:36 AM
    Added question about address_end

  • SQL query with dates

    WITH tab AS
    (select '1' id1, '2' id2,'30-04-2009' Date1,'102' amount from dual union all
    select '1' id1 , '1' id2,'15-04-2009' Date1, '100' amount from dual union all
    select '1' id1, '1' id2,'16-04-2009' Date1, '200' amount from dual union all
    select '2' id1, '1' id2, '01-05-2009' Date1, '150' amount from dual union all
    select '2' id1, '1' id2,'30-06-2009' Date1, '110' amount from dual
    select * from tab;
    WITH union_data AS
    (select '1' no,'01-04-2009' from_Date1,'30-04-2009' to_date from dual union all
    select '2' no ,'01-05-2009' from_Date1,'31-05-2009' to_date from dual union all
    select '3' no, '01-06-2009' from_Date1,'30-06-2009' to_date from dual union all
    select '4' no, '01-07-2009' from_Date1,'31-07-2009' to_date from dual
    select * from union_data;
    i need a query to sum the amout which falls on the particular from_date and to_date.here in the above case with id1 and id2 as primary key
    from the table tab date1 for the first row is 30-04-2009 which falls in the no - 1 in the second table
    from the table tab date1 for the second row is 15-04-2009 which again falls in the no - 1 in the second table
    from the table tab date1 for the third row is 16-04-2009 which again falls in the no - 1 in the second table
    from the table tab date1 for the fourth row is 01-05-2009 which falls in the no - 2 in the second table
    from the table tab date1 for the fourth row is 30-06-2009 which falls in the no - 3 in the second table
    so the output should as below which should be return as rows which the table will be the following rows
    id1,id2,no1_amnt,no2_amnt,no3_amnt,no4_amnt,no5_amnt
    WITH result AS
    (select '1' id1,'2' id2,'102' no1_amnt,'null' no2_amnt,'null' no3_amnt,'null' no4_amnt,'null' no5_amnt from dual union all
    select '2' id1,'1' id2,'null' no1_amnt,'150' no2_amnt,'110' no3_amnt,'null' no4_amnt,'null' no5_amnt from dual union all
    select '1' id1,'1' id2,'300' no1_amnt,'null' no2_amnt,'null' no3_amnt,'null' no4_amnt,'null' no5_amnt from dual
    select * from result;
    The above result as the first table got 3 combination of primary key id1 and id2. and then looked up in the second table from_date and to_date and sum up the amount.
    Please help to get the query

    Posting late as the forum was not working some time back :(
    WITH tab AS
    select '1' id1, '2' id2,to_date('30-04-2009','dd-mm-yyyy') Date1,'102' amount from dual
    union all
    select '1' id1 , '1' id2,to_date('15-04-2009','dd-mm-yyyy') Date1, '100' amount from dual
    union all
    select '1' id1, '1' id2,to_date('16-04-2009','dd-mm-yyyy') Date1, '200' amount from dual
    union all
    select '2' id1, '1' id2, to_date('01-05-2009','dd-mm-yyyy') Date1, '150' amount from dual
    union all
    select '2' id1, '1' id2,to_date('30-06-2009','dd-mm-yyyy') Date1, '110' amount from dual
    union_data AS
    select '1' no,to_date('01-04-2009','dd-mm-yyyy') from_Date1,to_date('30-04-2009','dd-mm-yyyy') to_date1 from dual
    union all
    select '2' no ,to_date('01-05-2009','dd-mm-yyyy') from_Date1,to_date('31-05-2009','dd-mm-yyyy') to_date1 from dual
    union all
    select '3' no, to_date('01-06-2009','dd-mm-yyyy') from_Date1,to_date('30-06-2009','dd-mm-yyyy') to_date1 from dual
    union all
    select '4' no, to_date('01-07-2009','dd-mm-yyyy') from_Date1,to_date('31-07-2009','dd-mm-yyyy') to_date1 from dual
    select id1, id2, max(decode(no,1,amount)) no1, max(decode(no,2,amount)) no2, max(decode(no,3,amount)) no3, max(decode(no,4,amount)) no4, max(decode(no,5,amount)) no5
      from (
    select a.id1, a.id2, b.no, sum(a.amount) amount
      from tab a
      join union_data b
        on a.date1 between b.from_date1 and b.to_date1
    group by id1, id2, no)
    group by id1, id2

  • Dynamic query with Data Access Layer

    I have a program that has a multiselect box (JSP form) to select certifications and then search to see which employee may have them.
    I have no issues when searching by only one, but if I select multiple certifications from the multiselect box, it doesn't work. I've tried and tried and I can't seem to figure this out.
    Below is the code for returning employees that match what certifications were chosen. Again, it works fine if only 1 was selected. I wish for it to return only the employees that match all selections.
    the arguments passed to the DataAccess Layer are an array of certification ID's and the size variable is how many certifications were chosen. The for loop is supposed to dynamically append to the end of the query an extra "AND" sql operator to match up. The 3 tables selected in the query are Employee (a list of employees and ID's), Certificates (a list of possible certificates and their ID's) and Employee_Certificate (a table that matches which employees have which certificates).
    What am I doing wrong?
    public List certSearch(int cert[], int size) throws Exception{
             // connection instance
             ArrayList list = new ArrayList();
             Connection connection=null;
             PreparedStatement pstatement = null;
             try
                    list.clear();
                    StringBuffer queryString = new StringBuffer("SELECT * from EMPLOYEE, EMPLOYEE_CERTIFICATE, CERTIFICATE" +
                                         " WHERE employee_certificate.employee_id = employee.employee_id " +
                                         "AND certificate.certificate_id = employee_certificate.certificate_id ");
                    for (int incr = 0; incr < size; incr++){
                        queryString.append("AND certificate.certificate_id = " + cert[incr] + " ");
                    String query;
                    query = queryString.toString();
                    // Send query to database and store results.
                    Class.forName(Driver);
                    //Establish network connection to the db
                    connection = (Connection) DriverManager.getConnection(url, username, password);
                    pstatement = (PreparedStatement) connection.prepareStatement(query);
                    ResultSet rs = pstatement.executeQuery();
                    while (rs.next())
                        Employee emp = new Employee();
                        int empID=Integer.parseInt(rs.getString("employee_id"));
                        String first=rs.getString("first_name");
                        String last=rs.getString("last_name");
                        emp.setID(empID);
                        emp.setFirstName(first);
                        emp.setLastName(last);
                        list.add(emp);
               catch(Exception readerr)
                    System.err.println("Error reading  "+ readerr);
               finally
                try
                    // close the connection so it can be returned to the
                    // connection pool then return the SubjectCounselor instance
                    connection.close();
                catch (SQLException ex)
                       System.err.println("Error reading employee data: " + ex);
                return list;
        }Edited by: Snadinator on Aug 1, 2009 1:35 PM

    You don't get it.
    This should work :
    public List certSearch(int cert[], int size) throws Exception{
             // connection instance
             ArrayList list = new ArrayList();
             Connection connection=null;
             PreparedStatement pstatement = null;
             try
                    list.clear();
                    String query = buildQuery(cert);
                    // Send query to database and store results.
                    Class.forName(Driver);
                    //Establish network connection to the db
                    connection = (Connection) DriverManager.getConnection(url, username, password);
                    pstatement = (PreparedStatement) connection.prepareStatement(query);
                    ResultSet rs = pstatement.executeQuery();
                    while (rs.next())
                        Employee emp = new Employee();
                        int empID=Integer.parseInt(rs.getString("employee_id"));
                        String first=rs.getString("first_name");
                        String last=rs.getString("last_name");
                        emp.setID(empID);
                        emp.setFirstName(first);
                        emp.setLastName(last);
                        list.add(emp);
               catch(Exception readerr)
                    System.err.println("Error reading  "+ readerr);
               finally
                try
                    // close the connection so it can be returned to the
                    // connection pool then return the SubjectCounselor instance
                    connection.close();
                catch (SQLException ex)
                       System.err.println("Error reading employee data: " + ex);
                return list;
        // I used the MySQL syntax; if it doesn't work : just enclose the values by single quotes
        private String buildQuery(int[] cert) {
            StringBuffer queryString = new StringBuffer("SELECT * from EMPLOYEE, EMPLOYEE_CERTIFICATE, CERTIFICATE" +
                    " WHERE employee_certificate.employee_id = employee.employee_id " +
                    "AND certificate.certificate_id = employee_certificate.certificate_id " +
                    "AND certificate.certificate_id IN ( ");
            queryString.append(cert[0]);
            for (int i = 1; i < cert.length; i++) {
                queryString.append(" ,");
                queryString.append(cert);
    queryString.append(" )");
    return queryString.toString();

  • SQL Query with Date Range

    I have a query that will retrieve order between selected dates. It works great but returns no record if the 2 dates are the same.
    Example:
    Orders between 9-1-2010 and 9-30-2010 retunes 35 records.
    But if I select between -9-25-2010 and 9-25-2010, so I can see all order from this 1 day, it returns 1 records, and I know there are records for that day!
    Here's my query:
    <%
    Dim rsOrders__MMColParam
    rsOrders__MMColParam = "1"
    If (Request.QueryString("datefrom") <> "") Then
      rsOrders__MMColParam = Request.QueryString("datefrom")
    End If
    %>
    <%
    Dim rsOrders__MMColParam2
    rsOrders__MMColParam2 = "1"
    If (Request.QueryString("dateto") <> "") Then
      rsOrders__MMColParam2 = Request.QueryString("dateto")
    End If
    %>
    <%
    Dim rsOrders
    Dim rsOrders_cmd
    Dim rsOrders_numRows
    Set rsOrders_cmd = Server.CreateObject ("ADODB.Command")
    rsOrders_cmd.ActiveConnection = MM_ezcaldatasource_STRING
    rsOrders_cmd.CommandText = "SELECT * FROM dbo.orders WHERE (OrderDate between ? and ?) AND Finalized  = 1"
    rsOrders_cmd.Prepared = true
    rsOrders_cmd.Parameters.Append rsOrders_cmd.CreateParameter("param1", 135, 1, -1, rsOrders__MMColParam) ' adDBTimeStamp
    rsOrders_cmd.Parameters.Append rsOrders_cmd.CreateParameter("param2", 135, 1, -1, rsOrders__MMColParam2) ' adDBTimeStamp
    Set rsOrders = rsOrders_cmd.Execute
    rsOrders_numRows = 0
    %>

    2 possible
    1) Change the column's data type from a datetime to a date if supported by your DBMS
    2) Use date math to always add 1 day to the end date. So instead of the end date of 9-25-2010 (00:00) it will be 9-26-2010 (00:00)

  • Help in building Toplink query with Date

    Hi,
    Can any anybody help me on how to build the toplink expression for the date.
    We are passing the date object and I'm getting the date as (Eg:"Sat May 31 16:34:35 EDT 2008").
    When I passing in like this I'm not able to det the data although I got data in the database.
    Expression dateExp = builder.get(testDate").equal("zzzzz.getDate()");
    Any help is appreciated.
    Thanks,
    Basil

    Hello Basil,
    Can you turn on logging and post the sql that gets generated? Also, what is the database/driver version being used, and what is the database column type for the date? This could be a problem with the precision of the date object being passed in not matching the date objects used in the database. If you read an object by its primary key, is the date infomation populated correctly?
    Best Regards,
    Chris

  • Query with date

    Hi,
    The query has the following output which is built by multiple tables :
    Cust No. Invoice Date Balance
    1 01-jan-06 100
    1 10-mar-06 200
    1 20-mar-06 50 ----->
    2 15-jan-06 25
    2 02-mar-06 50
    2 10-mar-06 100 ----->
    Suppose if I enter the invoice date as 'MAR-06' I should get the output of two records only indicated by arrow....
    1 20-mar-06 50 ----->
    2 10-mar-06 100 ----->
    Please let me know to frame the query.
    Thanks....

    in your query you need to add
    where TO_CHAR(TRUNC( Inoice_date, 'MONTH'), 'MON-YYYY' ) = 'MAR-2006'
    By the way, you have one more mar-2006 row well two more
    Cust No. Invoice Date Balance
    1 01-jan-06 100
    1 10-mar-06 200 ------>here
    1 20-mar-06 50 ----->
    2 15-jan-06 25
    2 02-mar-06 50 -----> and here
    2 10-mar-06 100 ----->

Maybe you are looking for

  • Reversal of Depreciation posted already in a closed financial year

    Hi I met with a scenario , where in a financial year 2009 ( Apr to Mar) I acquired an asset on 01.04.2009. The whole year depreciation was run and posted. How to reverse the posted depreciation, a) for the entire year b) for a selected period. Thanks

  • Images to Video (Sun Example doesn't work for me)

    Hi every one :) I'm trying to convert some jpg images into movie file. I saw the [Sun's example|http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/solutions/JpegImagesToMovie.html] , but when I try to execute I have a DataSink error: Can

  • Error while using DBMS_MVIEW

    All, I am facing an error while running the below utility . DB Version : 10.1.0.3.0 begin dbms_mview.EXPLAIN_REWRITE( query => 'SELECT one_voice_industry ,quarter, SUM(license_revenue) FROM rep037_fin_iot WHERE 1 = 1 GROUP BY one_voice_industry,quart

  • Problem for retriveing servlet class file (error in DD) I think so

    hi to all , my deployment descriptor is here .... I tried to access servlet ... I got the response is like that The requested Resource is not available why its happening ? <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app     PUBLIC "-//S

  • Part I and Part II in migo

    HI, Can anyone please explain me what is part I and Part II in migo..when do we do part I and Part II. I am really confused. Please give me some inputs Thank you