Help with SQL Query and dates

I am trying to return results between a year or 365 days. I need to run this at any time and return a year prior. I'm not getting any results? Any help? THX!
SELECT
NAME.ID,
Activity.UF_2,
Name.FIRST_NAME,
Name.LAST_NAME,
Name.EMAIL,
Activity.TRANSACTION_DATE
FROM
Activity INNER
JOIN Name
ON Activity.ID
= Name.ID
Where
activity.TRANSACTION_DATE
BETWEEN
CAST(CAST(DATEADD(DAY,
-365,
GETDATE())
AS
DATE)
AS
DATETIME)
AND
DATEADD
(SECOND,
-1,
DATEADD(DAY,
1,
CAST(CAST(DATEADD(DAY,
-365,
GETDATE())
AS
DATE)
AS
DATETIME)))
and Activity.UF_1
=
'a'
and Activity.UF_2
=
'NAT'

Where activity.TRANSACTION_DATE >= DATEADD(YEAR, -1, GETDATE()) AND activity.TRANSACTION_DATE < GETDATE()

Similar Messages

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
    The query should return the following data set
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

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

  • Need help with sql query dates

    Hi,
    I have a sql query where i need to extract some info between given dates. The where clause of this query is as follows:
    WHERE CPD_BUS_UNIT=:ESI_PRM_1
    AND CPD_VOUCHER_DATE >= :P_DATE_FROM
    AND CPD_VOUCHER_DATE < (:P_DATE_TO+1)
    When i execute the query in toad, i can view the data but not the execution plan.It gives an error ORA-00932-Inconsistent Datatypes.
    But when i remove (+1) from :P_DATE_TO, i can c the execution plan and data. Will the data be different from the previous one.
    Please suggest how to rewrite the query.

    Can you please give it a try?
    WHERE CPD_BUS_UNIT=:ESI_PRM_1
    AND CPD_VOUCHER_DATE >= :to_date(P_DATE_FROM)
    AND CPD_VOUCHER_DATE < (to_date(:P_DATE_TO)+1) Regards

  • Help with SQL query invloving time operations

    I have created 2 tables in my SQL. One is the user_info table which stores the time of login and timezone of login for each user. The other is the post_table which stores the postid, user who makes the post, time of post and timezone for each posts.
    CREATE TABLE user_info
    user_id VARCHAR(20),
    login_date DATE,
    login_time_zone VARCHAR(20),
    PRIMARY KEY (user_id)
    CREATE TABLE post_table
    post_id VARCHAR(20), 
    user_id VARCHAR(20),
    datepost DATE, 
    time_zone VARCHAR(20),
    PRIMARY KEY (post_id),
    FOREIGN KEY (user_id) REFERENCES user_info(user_id) ON DELETE CASCADE
    ) ;Some sample data for my tables is as below -
    INSERT INTO user_info VALUES( 'u1', to_date('9/17/2009 20:00','MM/DD/YYYY mi:ss'), -2 );
    INSERT INTO user_info VALUES( 'u2', to_date('9/17/2009 19:55','MM/DD/YYYY mi:ss'), -4 );
    INSERT INTO post_table VALUES( 'p1', 'u1', to_date('9/17/2009 20:50','MM/DD/YYYY mi:ss'), 6 );
    INSERT INTO post_table VALUES( 'p2', 'u2', to_date('9/17/2009 20:30','MM/DD/YYYY mi:ss'), -5 );
    INSERT INTO post_table VALUES( 'p3', 'u2', to_date('9/18/2009 6:00','MM/DD/YYYY mi:ss'), 2 );
    INSERT INTO post_table VALUES( 'p4', 'u1', to_date('9/17/2009 21:00','MM/DD/YYYY mi:ss'), -3 );I need to write an SQL query which - finds the user(s) whose time difference between the login time and the latest time when he/she writes a post is the smallest. I need to consider the timezones here as well.
    I am unsure if time_zone should be of type VARCHAR or TIMESTAMP so have created it as VARCHAR in my tables.
    Someone please help me form this query.
    PS : How do I user <code> tags in this forum to write sql statements.
    Edited by: user11994430 on Oct 9, 2009 5:59 PM

    I tried with the following test data
    INSERT INTO user_info VALUES( 'u1', to_date('9/17/2009 20:00','MM/DD/YYYY mi:ss'), 1 );
    INSERT INTO user_info VALUES( 'u2', to_date('9/16/2009 13:00','MM/DD/YYYY mi:ss'), 1 );
    INSERT INTO user_info VALUES( 'u3', to_date('9/18/2009 15:00','MM/DD/YYYY mi:ss'), 0 );
    INSERT INTO user_info VALUES( 'u4', to_date('9/20/2009 17:00','MM/DD/YYYY mi:ss'), 0 );
    INSERT INTO user_info VALUES( 'u5', to_date('9/14/2009 3:00','MM/DD/YYYY mi:ss'), -3 );
    INSERT INTO user_info VALUES( 'u6', to_date('9/15/2009 6:00','MM/DD/YYYY mi:ss'), -3 );
    INSERT INTO user_info VALUES( 'u7', to_date('9/16/2009 7:00','MM/DD/YYYY mi:ss'), 0 );
    INSERT INTO user_info VALUES( 'u8', to_date('9/17/2009 8:00','MM/DD/YYYY mi:ss'), -8 );
    INSERT INTO user_info VALUES( 'u9', to_date('9/18/2009 9:00','MM/DD/YYYY mi:ss'), 0 );
    INSERT INTO user_info VALUES( 'u10', to_date('9/19/2009 10:00','MM/DD/YYYY mi:ss'), 1 );
    INSERT INTO user_info VALUES( 'u11', to_date('9/20/2009 11:00','MM/DD/YYYY mi:ss'), -5 );
    INSERT INTO user_info VALUES( 'u12', to_date('9/21/2009 19:00','MM/DD/YYYY mi:ss'), -8 );
    INSERT INTO user_info VALUES( 'u13', to_date('9/1/2009 4:00','MM/DD/YYYY mi:ss'), -3 );
    INSERT INTO user_info VALUES( 'u14', to_date('9/22/2009 7:00','MM/DD/YYYY mi:ss'), 1 );
    INSERT INTO user_info VALUES( 'u15', to_date('9/24/2009 23:00','MM/DD/YYYY mi:ss'), 1 );
    INSERT INTO user_info VALUES( 'u16', to_date('9/25/2009 11:00','MM/DD/YYYY mi:ss'), 1 );
    INSERT INTO user_info VALUES( 'u17', to_date('9/26/2009 18:00','MM/DD/YYYY mi:ss'), -4 );
    INSERT INTO user_info VALUES( 'u18', to_date('9/27/2009 13:00','MM/DD/YYYY mi:ss'), -8 );
    INSERT INTO user_info VALUES( 'u19', to_date('9/17/2009 18:00','MM/DD/YYYY mi:ss'), -5 );
    INSERT INTO user_info VALUES( 'u20', to_date('9/29/2009 22:00','MM/DD/YYYY mi:ss'), -8 );
    INSERT INTO user_info VALUES( 'u21', to_date('9/30/2009 5:00','MM/DD/YYYY mi:ss'), -8 );
    INSERT INTO user_info VALUES( 'u22', to_date('9/15/2009 7:00','MM/DD/YYYY mi:ss'), -4 );
    INSERT INTO user_info VALUES( 'u23', to_date('9/16/2009 17:00','MM/DD/YYYY mi:ss'), -8 );
    INSERT INTO user_info VALUES( 'u24', to_date('9/17/2009 19:00','MM/DD/YYYY mi:ss'), 0 );
    INSERT INTO user_info VALUES( 'u25', to_date('9/18/2009 22:00','MM/DD/YYYY mi:ss'), -5 );
    INSERT INTO user_info VALUES( 'u26', to_date('9/19/2009 15:00','MM/DD/YYYY mi:ss'), 1 );
    INSERT INTO user_info VALUES( 'u27', to_date('9/20/2009 23:00','MM/DD/YYYY mi:ss'), 1 );
    INSERT INTO post_table VALUES('p1', 'u26', to_date('9/14/2009 18:00','MM/DD/YYYY mi:ss'), -5 ) ;
    INSERT INTO post_table VALUES('p2', 'u2',  to_date('7/1/2009 15:00','MM/DD/YYYY mi:ss'), 1 ) ;
    INSERT INTO post_table VALUES('p3',  'u2',  to_date('7/20/2009 20:00','MM/DD/YYYY mi:ss'), 1  );
    INSERT INTO post_table VALUES('p4', 'u5',  to_date('7/20/2009 22:00','MM/DD/YYYY mi:ss'), 1) ;
    INSERT INTO post_table VALUES( 'p5',  'u2', to_date('7/21/2009 10:00','MM/DD/YYYY mi:ss'), 1  );
    INSERT INTO post_table VALUES(  'p6',  'u8',  to_date('8/1/2009 20:00','MM/DD/YYYY mi:ss'), -8  );
    INSERT INTO post_table VALUES( 'p7',  'u10', to_date('5/3/2009 15:00','MM/DD/YYYY mi:ss'), -3 ) ;
    INSERT INTO post_table VALUES( 'p8',  'u25', to_date('9/15/2009 20:00','MM/DD/YYYY mi:ss'), -5 ) ;
    INSERT INTO post_table VALUES(  'p9',  'u6', to_date('9/7/2009 19:00','MM/DD/YYYY mi:ss'), -3 ) ;
    INSERT INTO post_table VALUES( 'p10',  'u10', to_date('7/22/2009 10:00','MM/DD/YYYY mi:ss'), 1 ) ;
    INSERT INTO post_table VALUES( 'p11',  'u9',  to_date('7/7/2009 13:00','MM/DD/YYYY mi:ss'), 0) ;
    INSERT INTO post_table VALUES(  'p12', 'u2',  to_date('7/30/2009 11:00','MM/DD/YYYY mi:ss'), 1  );
    INSERT INTO post_table VALUES(  'p13', 'u10',  to_date('7/22/2009 8:00','MM/DD/YYYY mi:ss'), 1  );
    INSERT INTO post_table VALUES(  'p14',  'u6', to_date('5/30/2009 23:00','MM/DD/YYYY mi:ss'), 1  );
    INSERT INTO post_table VALUES(  'p15', 'u3',  to_date('5/31/2009 2:00','MM/DD/YYYY mi:ss'), 0 ) ;
    INSERT INTO post_table VALUES( 'p16', 'u12',  to_date('6/20/2009 7:00','MM/DD/YYYY mi:ss'), -8 ) ;
    INSERT INTO post_table VALUES(  'p17', 'u20',  to_date('6/20/2009 9:00','MM/DD/YYYY mi:ss'), -8) ;
    INSERT INTO post_table VALUES(  'p18','u27',  to_date('9/15/2009 11:00','MM/DD/YYYY mi:ss'), -5 );
    INSERT INTO post_table VALUES(  'p19','u26', to_date('7/1/2009 20:00','MM/DD/YYYY mi:ss'), 0 ) ;
    INSERT INTO post_table VALUES(  'p20', 'u25',  to_date('7/2/2009 17:00','MM/DD/YYYY mi:ss'), -5 );
    INSERT INTO post_table VALUES(  'p21', 'u27',  to_date('7/3/2009 20:00','MM/DD/YYYY mi:ss'), 1) ;
    INSERT INTO post_table VALUES( 'p22',  'u2',  to_date('9/15/2009 13:00','MM/DD/YYYY mi:ss'), 1 ) ;
    INSERT INTO post_table VALUES( 'p23',  'u21',  to_date('5/30/2009 17:00','MM/DD/YYYY mi:ss'), -8  );
    INSERT INTO post_table VALUES( 'p24',  'u25', to_date('8/30/2009 20:00','MM/DD/YYYY mi:ss'), -5  );
    INSERT INTO post_table VALUES(  'p25',  'u18', to_date('9/13/2009 18:00','MM/DD/YYYY mi:ss'), -8  );
    INSERT INTO post_table VALUES(  'p26',  'u11',  to_date('9/9/2009 13:00','MM/DD/YYYY mi:ss'), -8  );
    INSERT INTO post_table VALUES( 'p27',  'u23',  to_date('9/10/2009 1:00','MM/DD/YYYY mi:ss'), -5  );
    INSERT INTO post_table VALUES( 'p28',  'u22', to_date('9/10/2009 14:00','MM/DD/YYYY mi:ss'), -4  );The output I get is
    USER_ID
    u25
    u9
    u20
    u5
    u27
    u8
    u21
    u23
    u22
    u26
    u10
    USER_ID
    u3
    u12
    u18
    u2
    u6
    u11
    17 rows selected.

  • Help with sql query the status of  A/P Reserve Invoice

    Hi,
    I am trying to write a query which lists all A/P Reserve Invoice info with OPEN status.
    I check the OPCH table and cannot find the rule to tell the status.
    The "DocStatus" field has two values only: 'O' for open and 'C' for closed.
    However, the status of A/P Reserve Invoice are OPEN, CLOSED, DELIVERED, PAID, etc.
    I try to use DocStatus field to filter, but the result does not match what I see in SAP.
    Could you please give me some hints about how to get the data I need? Thank you.
    Best regards,
    Sylvia
    Edited by: csylvia on Jun 23, 2011 5:54 AM

    Hi Darius,
    Thanks for your reply.
    However, I don't know what is the relationship between Purchase order and A/P Reserve Invoice.
    Do you mean using "SELECT T0.DocEntry FROM OPCH T0, OPOR T1 WHERE T0.DocNum = T1.DocNum AND T1.DocStatus = 'O';" to query the A/P Reserve Invoice data with OPEN status?
    But the result is not what I want.
    The result of "*SELECT * FROM OPOR WHERE DocStatus = 'O';*" is also not.
    I'd like to query A/P Reserve Invoice list with OPEN status, and I try the following sql query:
    SELECT DocEntry FROM OPCH WHERE DocStatus = 'O' AND InvntSttus = 'O';
    The result is close to what I need, but it's not exactly correct.
    Moreover, I don't think the sql query conditions is accurate.
    Please give me some advice. Thank you.
    Best regards,
    Sylvia

  • Help with SQL query into Crystal

    Afternoon all,
    I am trying to convert the following SQL query into Crystal by using the tables given in the query however the relationship given in the query is bit awkward, in a sense that I cannot create a relationship under Crystal desgin.
    Here is the query
    select count(order_progressed.order_no),reason_code
    from order_progressed,lab_reasons, rework_groups
    where
    order_progressed.date_created=Today
    and (order_progressed.order_status=from_gate
    and lab_reasons.reason_code between from_reason and to_reason)
    group by lab_reasons.reason_code
    order by 2
    We have three tables
    1: Order_Progressed
    2: Lab Reasons
    3: Rework_Groups
    Order_progressed can be linked with rework_group by Status (if you see the line order_progressed.order_status=from_gate)
    However how to link the following line?
    lab_reasons.reason_code between from_reason and to_reason
    I mean when I try to link it by Lab Reasons.Reason Code to From_reason, to reason, it doesn't seem to work.
    The report is grouped by Lab Reasons. Reason Code, so I really have to some how create a relationship between Lab Reasons table and Rework_Group table.
    This is what I get when I run the same query into Crystal using the relationship
    SELECT lab_reasons.reason_code, order_progressed.date_created, order_progressed.order_no
    FROM   maxmast.lab_reasons lab_reasons, kevin.order_progressed order_progressed,
    roger.rework_groups rework_groups
    WHERE  (order_progressed.order_status=rework_groups.from_gate) AND
    ((lab_reasons.reason_code=rework_groups.from_reason) AND
    (lab_reasons.reason_code=rework_groups.to_reason)) AND (order_progressed.date_created>={ts
    '2008-01-01 00:00:00'} AND order_progressed.date_created<={ts '2008-12-17 00:00:00'})
    Any ideas?
    Many thanks
    Kind Regards
    Jehanzeb

    Sastry I didn't understand why did you use Lab_reasons.reason_code twice in your SQL.
    What I have done since I posted this thread,
    I created a command like this
    Select *
    from rework_groups,lab_reasons
    where
    lab_reasons.reason_code between from_reason and to_reason
    Then I took out the lab_reasons table and rework_groups table, then I linked the order_status from Order_progressed table to From_gate of the newly created table (I called it Reason_Code).
    This made the report running but it is crunching quite allot of numbers. I wonder if I made a mistake somewhere?
    Oh and please note, I'd like to create an SQL (if need be) without the date entry which was done in the original SQL because I'd like to setup my own date range within Crystal Reports instead of getting passed by SQL itself.
    This is how it looks like in Crystal now.
    sae1_live
    SELECT order_progressed.date_created, order_progressed.order_no, order_progressed.order_status
    FROM   kevin.order_progressed order_progressed
    WHERE  (order_progressed.date_created>={ts '2008-01-01 00:00:00'} AND
    order_progressed.date_created<={ts '2008-12-17 00:00:00'})
    EXTERNAL JOIN order_progressed.order_status={?sae1_live: Reason_Code.from_gate}
    sae1_live
    Select *
    from rework_groups, lab_reasons
    where lab_reasons.reason_code between from_reason and to_reason
    EXTERNAL JOIN Reason_Code.from_gate={?sae1_live: order_progressed.order_status}
    Regards
    Jehanzeb

  • I need help with SQL query

    Hi All,
    I have a problem in the query below. When I run the query I got a pop-up screen to ente value for
    :total_balance,
    :emp_code,
    :from_date,
    :to_date
    total_balance supose to be a result of a calculation.
    Your assistance is apreciated. Thanks,
    Ribhi
    select      FK_VOUCHERSERIAL_N,
         FK_VOUCHERVALUE_DA,
         DESCRIPTION,
         nvl(AMOUNT,0) amount,
         TYPE,
         Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) postive_amount,
         Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) negative_amount,
         Accnt101.total_balanceformula(:total_balance, EMPLOYEE_TRANSACTI.TYPE,Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) ,Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) , nvl(AMOUNT,0)) total_balance
    from      EMPLOYEE_TRANSACTI
    where     FK_EMPLOYEENUMBER0=:emp_code
    and     STATUS=1
    and     FK_VOUCHERVALUE_DA<=:to_date
    and     FK_VOUCHERVALUE_DA>=:from_date
    and     ((TYPE >7 and TYPE <16)
         or (TYPE >34 and TYPE <43)
         or (TYPE =7)
         or (TYPE =18)
         or (TYPE >26 and TYPE <35)
         or (TYPE =17)
         OR (TYPE = 60)
         OR (TYPE = 70)
    OR (TYPE = 72)
    OR (TYPE = 73)
    OR (TYPE = 74)
         or (type = 21)
         or (type =24)
         or (type = 81)
         or (type = 82))
    order by      FK_VOUCHERVALUE_DA asc, FK_VOUCHERSERIAL_N asc, type desc

    Hi Satyaki,
    My problem is with SQL and PL/SQL codd. I managed to convert some of my reports and now I'm facing a problem with converted SQL and PL/SQL code. To give you an Idea the following is a sample of a converted report.
    Pls have a look. (p.s how can i post formated text)
    Thanks,
    Ribhi
    1 - XML template file
    <?xml version="1.0" encoding="UTF-8" ?>
    - <dataTemplate name="Accnt101" defaultPackage="Accnt101" version="1.0">
    - <properties>
    <property name="xml_tag_case" value="upper" />
    </properties>
    - <parameters>
    <parameter name="FROM_DATE" dataType="date" defaultValue="01/01/1998" />
    <parameter name="TO_DATE" dataType="date" defaultValue="31/12/1998" />
    <parameter name="EMP_CODE" dataType="number" defaultValue="44" />
    </parameters>
    <lexicals />
    - <dataQuery>
    - <sqlStatement name="employee_trans">
    - <![CDATA[
    select      FK_VOUCHERSERIAL_N,
         FK_VOUCHERVALUE_DA,
         DESCRIPTION,
         nvl(AMOUNT,0) amount,
         TYPE,
         Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) postive_amount,
         Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) negative_amount,
         Accnt101.total_balanceformula(:total_balance, EMPLOYEE_TRANSACTI.TYPE,Accnt101.negative_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) ,Accnt101.postive_amountformula(EMPLOYEE_TRANSACTI.TYPE, nvl(AMOUNT,0)) , nvl(AMOUNT,0)) total_balance
    from      EMPLOYEE_TRANSACTI
    where     FK_EMPLOYEENUMBER0=:emp_code
    and     STATUS=1
    and     FK_VOUCHERVALUE_DA<=:to_date
    and     FK_VOUCHERVALUE_DA>=:from_date
    and     ((TYPE >7 and TYPE <16)
         or (TYPE >34 and TYPE <43)
         or (TYPE =7)
         or (TYPE =18)
         or (TYPE >26 and TYPE <35)
         or (TYPE =17)
         OR (TYPE = 60)
         OR (TYPE = 70)
                    OR (TYPE = 72)
                    OR (TYPE = 73)
                    OR (TYPE = 74)
         or (type = 21)
         or (type =24)
         or (type = 81)
         or (type = 82))
    order by      FK_VOUCHERVALUE_DA asc, FK_VOUCHERSERIAL_N asc, type desc
      ]]>
    </sqlStatement>
    - <sqlStatement name="employee">
    - <![CDATA[
    select NAME,NUMBER0
    from EMPLOYEE
    where  NUMBER0=:emp_code
      ]]>
    </sqlStatement>
    </dataQuery>
    <dataTrigger name="beforeReportTrigger" source="Accnt101.beforereport" />
    - <dataStructure>
    - <group name="G_employee_trans" dataType="varchar2" source="employee_trans">
    <element name="FK_VOUCHERSERIAL_N" dataType="number" value="FK_VOUCHERSERIAL_N" />
    <element name="FK_VOUCHERVALUE_DA" dataType="date" value="FK_VOUCHERVALUE_DA" />
    <element name="DESCRIPTION" dataType="varchar2" value="DESCRIPTION" />
    <element name="AMOUNT" dataType="number" value="AMOUNT" />
    <element name="postive_amount" dataType="number" value="postive_amount" />
    <element name="negative_amount" dataType="number" value="negative_amount" />
    <element name="total_balance" dataType="number" value="total_balance" />
    <element name="TYPE" dataType="number" value="TYPE" />
    <element name="CS_1" function="sum" dataType="number" value="G_employee_trans.total_balance" />
    </group>
    - <group name="G_employee" dataType="varchar2" source="employee">
    <element name="NUMBER0" dataType="number" value="NUMBER0" />
    <element name="NAME" dataType="varchar2" value="NAME" />
    </group>
    <element name="balance" dataType="number" value="Accnt101.balance_p" />
    <element name="CS_2" function="count" dataType="number" value="G_employee.NUMBER0" />
    <element name="CS_3" function="count" dataType="number" value="G_employee_trans.AMOUNT" />
    </dataStructure>
    </dataTemplate>
    2 - PLS/SQL package
    CREATE OR REPLACE PACKAGE Accnt101 AS
         from_date     date;
         to_date     date;
         emp_code     number;
         balance     number := 0 ;
         function postive_amountformula(TYPE in number, amount in number) return number ;
         function negative_amountformula(TYPE in number, amount in number) return number ;
         function BeforeReport return boolean ;
         function total_balanceformula(total_balance in number, TYPE in number, negative_amount in number, postive_amount in number, amount in number) return number ;
         Function balance_p return number;
    END Accnt101;
    3- Package Body
    CREATE OR REPLACE PACKAGE BODY Accnt101 AS
    function postive_amountformula(TYPE in number, amount in number) return number is
    begin
         if ((TYPE>26 and TYPE<35)
              or (TYPE=17))
         then
              return(amount);
         elsif (type = 70)and (amount >=0) then
              return (amount) ;
    elsif (type = 72)and (amount >=0) then
              return (amount) ;
    elsif (type = 73)and (amount >=0) then
              return (amount) ;
    elsif (type = 74)and (amount >=0) then
              return (amount) ;
         elsif (type = 60)and (amount >=0) then
              return (amount) ;
         else
              return (null) ;
         end if;
    RETURN NULL; end;
    function negative_amountformula(TYPE in number, amount in number) return number is
    begin
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)
              or (TYPE=18)
              or (type=21)
              or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(amount);
         elsif (type = 70)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 72)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 73)and (amount <0) then
              return (abs (amount)) ;
    elsif (type = 74)and (amount <0) then
              return (abs (amount)) ;
         elsif (type = 60)and (amount <0) then
              return (abs(amount)) ;
         else
              return (null) ;
         end if;
    RETURN NULL; end;
    function BeforeReport return boolean is
    var_pos     number(15,3) ;
    var_neg     number(15,3) ;
    beg_bal     number(15,3) ;
    Begin
    begin
    select sum (nvl(amount,0)) into beg_bal
         from EMPLOYEE_TRANSACTI
         where (TYPE=99 or type = 92 or type = 93 or type = 94)
         and to_char(from_date,'YYYY')=to_char(date0,'YYYY')
         and FK_EMPLOYEENUMBER0=emp_code;
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         beg_bal := 0;
    end;
    begin
         select      sum(nvl(amount,0)) into var_pos
         from      EMPLOYEE_TRANSACTI
         where      
              (TYPE=17
              or type=60
              OR TYPE=70
    oR TYPE=72
    OR TYPE=73
    OR TYPE=74
              or (TYPE>26 and TYPE<35))
         and      fk_vouchervalue_da<from_date
         and      fk_vouchervalue_da>= trunc(from_date,'year')
         and      FK_EMPLOYEENUMBER0=emp_code;
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         var_pos := 0;
    end;
    Begin     
         select sum(nvl(amount,0)) into var_neg
         from EMPLOYEE_TRANSACTI
         where ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)
              or (TYPE=18)
              or (type=21)
              or (type=24)
              or (type= 81)
              or (type=82) )
         and fk_vouchervalue_da<from_date
         and fk_vouchervalue_da>= trunc(from_date,'year')
         and FK_EMPLOYEENUMBER0=emp_code;
         balance :=nvl(beg_bal,0) + nvl(var_pos,0) - nvl(var_neg,0);
         return(true);
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
         balance :=nvl(beg_bal,0) + nvl(var_pos,0) - nvl(var_neg,0);
              RETURN (TRUE);
    end;
    RETURN NULL; end;
    function total_balanceformula(total_balance in number, TYPE in number, negative_amount in number, postive_amount in number, amount in number) return number is
    begin
         if total_balance is null then
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)or (TYPE=18)
              or (type=21) or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(balance-negative_amount);
         elsif ((TYPE>26 and TYPE<35) or (TYPE=17))
              then
                   return(balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount >=0) then
                   return(balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount <0) then
                   return(balance-negative_amount);
         end if;
         else
         if ((TYPE>7 and TYPE<16)
              or (TYPE >34 and TYPE <43)
              or (TYPE=7)or (TYPE=18)
              or (type=21) or (type=24)
              or (type= 81)
              or (type=82))
         then
              return(total_balance-negative_amount);
         elsif ((TYPE>26 and TYPE<35) or (TYPE=17))
              then
                   return(total_balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount >=0) then
                   return(total_balance+postive_amount);
              elsif (type=70 or type=72 or type=73 or type=74
    or type=60) and (amount <0) then
                   return(total_balance-negative_amount);
         end if;
         end if ;
    RETURN NULL; end;
    Functions to refer Oracle report placeholders
    Function balance_p return number is
         Begin
         return balance;
         END;
    END Accnt101 ;

  • Help with CF Reports and Dates

    Can anyone here help me with
    This
    post ? I have been waiting for 3 days and after 4 posts no one
    has been able to answer, please help!! I'm stuck on my project only
    because of this. Thank you very, very much.
    Nelson.

    Sorry, I don't use cfreport so I would not be any help with
    what may be inside the total_sales_report_by_date.cfr template.
    However, shouldn't you be executin your query inside of your .cfm
    emplate, then passing the query result to your report as a query
    parameter within your cfreport tag, rather than passing the date
    parameters in cfreportparam tags?
    Phil

  • Help with SQL Query - MIN MAX - CTE?

    First and foremost, the SQL is handled dynamically - please ignore some of the crazy coding you see in the WHERE clauses ... its not an issue with the report, trust me.
    What my client needs is a summary by Facility, by Resource for each specific day - broken out in 3 distinct time blocks for that specific Resource at each distinct facility. For each Resource by Facility I need 3 rows - a row for their earliest AM appointment
    to their latest AM appointment (AMStart and AMStop below) - a row for their earliest PM appointment to their latest PM appointment (PMStart and PMStop below) and finally a row for their EVE appointments (EVEStart and EVEStop below).
    I thought doing a MIN and MAX on them would fix this and grouping it but I am missing something because my times for my AM are way off. For my test provider, I have set up a schedule that starts at 7:15 AM and spans to 11:45 AM. I created a break and had
    him re-start at 1:00 PM and go to 2:45 PM. No Evening clinic was made on this example.
    What I would hope to get back is 3 rows - an AM row with the earliest AMStart and latest AMStop time (with the PM and EVE pull NULL), a PM row(earliest and latest) (with the AM and EVE pull NULL) and finally my EVE with same concept.
    My current data set (1 row) - should have as 3 rows and my AM Start and Stop are wrong.
    Scheduledate = 01/21/2014      
    AMStart  = 10:00AM
    AMStop =  9:45AM      
    PMStart =       1:00PM
    PMStop =       2:45PM
    EveStart =       NULL
    EveStop =       NULL
    TotalTime = 375      
    Resource = Bailey MD, William R
    Facility = River Oaks
    /*Appointment Times report*/
    SET NOCOUNT ON
    DECLARE @Today DATETIME
    DECLARE @Tomorrow DATETIME
    SET @Today = '01/21/2014'
    SET @Tomorrow = DATEADD(d , 1 , '01/21/2014')
    DECLARE @tblTemp TABLE
    ApptSlotId INT ,
    Resource VARCHAR(60) ,
    ResourceId INT ,
    Start DATETIME ,
    Stop DATETIME ,
    AMStart DATETIME ,
    AMStop DATETIME ,
    PMStart DATETIME ,
    PMStop DATETIME ,
    EveStart DATETIME ,
    EveStop DATETIME ,
    Patient VARCHAR(256) ,
    [Column] VARCHAR(64) ,
    Facility VARCHAR(60) ,
    FacilityId INT ,
    Allocations VARCHAR(4096) ,
    Scheduledate VARCHAR(15)
    INSERT INTO @tblTemp
    SELECT
    ApptSlotid ,
    d.Listname ,
    d.DoctorFacilityId ,
    Start ,
    Stop ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    ' ' AS Patient ,
    CAST(aps.ListOrder AS VARCHAR(10)) AS [Column] ,
    f.ListName AS Facility ,
    aps.FacilityId ,
    dbo.sfnGetAllocsForSlot(aps.ApptSlotId) AS Allocations ,
    CONVERT(VARCHAR(15) , Start , 101)
    FROM
    ApptSlot aps
    JOIN Schedule s ON aps.ScheduleId = s.ScheduleId
    JOIN DoctorFacility df ON s.DoctorResourceId = df.DoctorFacilityId
    JOIN DoctorFacility f ON aps.FacilityId = f.DoctorFacilityId
    JOIN DoctorFacility d ON s.DoctorResourceId = d.DoctorFacilityId
    WHERE
    --Filter on resource
    NULL IS NOT NULL
    AND s.Doctorresourceid IN ( NULL )
    OR ( NULL IS NULL )
    AND (
    NULL IS NOT NULL
    AND aps.FacilityId IN ( NULL )
    OR ( NULL IS NULL )
    AND (
    Start >= @Today
    OR @Today IS NULL
    AND (
    Start < @Tomorrow
    OR @Tomorrow IS NULL
    AND ApptId IS NULL
    AND APS.ListOrder <> -1
    INSERT INTO @tblTemp
    SELECT DISTINCT
    ApptSlotid ,
    d.ListName ,
    d.DoctorFacilityId ,
    ApptStart ,
    ApptStop , -- need distinct because =ApptSlot can have more than row per appt
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    NULL ,
    CASE WHEN a.ApptKind = 1 THEN pp.Last + ', ' + pp.First
    WHEN a.ApptKind = 2 THEN 'Doctor Appt'
    WHEN a.ApptKind = 3 THEN 'Resource Appt'
    WHEN a.ApptKind = 5 THEN 'Block Out Appt'
    ELSE ''
    END AS Patient ,
    CASE WHEN aps.ListOrder IS NULL THEN 'Overbooked'
    ELSE CAST(aps.ListOrder AS VARCHAR(10))
    END AS [Column] ,
    f.ListName AS Facility ,
    a.FacilityId ,
    ISNULL(apt.Name , '<No Appointment Type>') AS Allocations ,
    CONVERT(VARCHAR(15) , ApptStart , 101) AS Scheduledate
    FROM
    Appointments a
    JOIN DoctorFacility f ON a.FacilityId = f.DoctorFacilityId
    LEFT JOIN PatientProfile pp ON a.OwnerId = pp.PatientProfileId
    LEFT JOIN ApptSlot aps ON a.AppointmentsId = aps.ApptId
    JOIN DoctorFacility d ON a.ResourceId = d.DoctorFacilityId
    LEFT JOIN ApptType apt ON a.ApptTypeId = apt.ApptTypeId
    WHERE
    NULL IS NOT NULL
    AND a.ResourceId IN ( NULL )
    OR ( NULL IS NULL )
    AND (
    NULL IS NOT NULL
    AND a.FacilityId IN ( NULL )
    OR ( NULL IS NULL )
    AND (
    ApptStart >= @Today
    OR @Today IS NULL
    AND (
    ApptStop < @Tomorrow
    OR @Tomorrow IS NULL
    AND (
    (ApptKind = 1
    AND ISNULL(Canceled , 0) = 0)
    UPDATE
    @tblTemp
    SET
    AMStart = Start ,
    AMStop = Stop
    FROM
    @tblTemp base
    WHERE
    CONVERT(TIME , start) < CONVERT(TIME , '12:00')
    UPDATE
    @tblTemp
    SET
    PMStart = Start ,
    PMStop = Stop
    FROM
    @tblTemp base
    WHERE
    CONVERT(TIME , start) > CONVERT(TIME , '12:00')
    AND CONVERT(TIME , start) < CONVERT(TIME , '17:00')
    UPDATE
    @tblTemp
    SET
    EveStart = Start ,
    EveStop = Stop
    FROM
    @tblTemp base
    WHERE
    CONVERT(TIME , start) > CONVERT(TIME , '17:00')
    --SELECT * FROM @tblTemp ORDER BY Start
    SELECT
    Scheduledate ,
    Start ,
    Stop ,
    [Column] ,
    Resource ,
    Facility ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.AMStart , 108) AS TIME) , 100) AS AMStart ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.AMStop , 108) AS TIME) , 100) AS AMStop ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.PMStart , 108) AS TIME) , 100) AS PMStart ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.PMStop , 108) AS TIME) , 100) AS PMStop ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.EveStart , 108) AS TIME) , 100) AS EveStart ,
    CONVERT(VARCHAR(60) , CAST(CONVERT(VARCHAR(60) , h.EveStop , 108) AS TIME) , 100) AS EveStop ,
    ISNULL(DATEDIFF(MI , h.AMStart , h.AMStop) , 0) + ISNULL(DATEDIFF(MI , h.PMStart , h.PMStop) , 0) + ISNULL(DATEDIFF(MI , h.EveStart , h.EveStop) , 0) AS TotTime
    INTO
    #tmp
    FROM
    @TblTemp h
    WHERE
    [Column] = 1
    ORDER BY
    START
    --SELECT * FROM #tmp
    SELECT
    Scheduledate ,
    MIN(AMStart) AS AMStart ,
    MAX(AMStop) AS AMStop ,
    MIN(PMStart) AS PMStart ,
    MAX(PMStop) AS PMStop ,
    MIN(EveStart) AS EveStart ,
    MAX(EveStop) AS EveStop ,
    SUM(TotTime) AS TotalTime ,
    Resource ,
    Facility
    FROM
    #tmp
    GROUP BY
    Resource ,
    Facility ,
    Scheduledate
    DROP TABLE #tmp
    SET NOCOUNT OFF

    Since there is some context missing, I don't get everything, but from your narrative, it seems likely you need something like:
    WITH CTE AS (
       SELECT keycol,
              period = CASE WHEN Start < '12:00' THEN 'AM'
                            WHEN Start < '17:00' THEN 'PM'
                            ELSE 'EVE'
                       END,
              start, stop
       FROM   tbl
    SELECT keycol, period, MIN(start), MAX(stop)
    FROM   CTE
    GROUP  BY keycol, period
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Setting Default value with SQL Query as Data Model

    Hi All,
    I am developing report based on SQL query.date set as 'SQL Query'. I have created two params start-date and end-date. I am fetching records from database between these two dates.
    I want to populate sysdate as a default values. I do not want to use datatemplate approach i mean using beforeReport trigger.
    Thansk,
    Vara

    Hi Vara,
    To set the default value for one of your parameters to SYSDATE you need to enter:
    {$SYSDATE()$}
    in the Default Value text box
    Is this what you require?
    Cheers
    Andy

  • Weird problem with mysql query and data table buttons !!!!

    Hi,
    I'm using jsc 2 update 1 on windows and mysql 4.1 . I have a page with a data table. One column of the data table contains "Details" buttons.
    Source query for the table is :
    SELECT tbl_tesserati.idtbl_tesserati idTesserato,
    tbl_tesserati.num_tessera,
    tbl_tesserati.nome,
    tbl_societa.codice_meccanografico
    FROM tbl_tesserati
    INNER JOIN tbl_rel_tesserato_discipline_societa ON tbl_tesserati.idtbl_tesserati = tbl_rel_tesserato_discipline_societa.id_tesserato
    INNER JOIN tbl_cariche ON      tbl_rel_tesserato_discipline_societa.id_carica = tbl_cariche.idtbl_cariche
    INNER JOIN tbl_qualifiche ON      tbl_rel_tesserato_discipline_societa.id_qualifica = tbl_qualifiche.idtbl_qualifiche
    INNER JOIN tbl_discipline ON      tbl_rel_tesserato_discipline_societa.id_disciplina = tbl_discipline.idtbl_discipline
    INNER JOIN tbl_societa ON      tbl_rel_tesserato_discipline_societa.id_societa = tbl_societa.idtbl_societa
    LEFT JOIN tbl_province ON tbl_societa.provincia_sede_sociale = tbl_province.idtbl_province
    LEFT JOIN tbl_comuni ON tbl_societa.comune_sede_sociale = tbl_comuni.idtbl_comuni
    LEFT JOIN tbl_rel_tesserato_discipline_praticate ON tbl_rel_tesserato_discipline_praticate.tessera_id=
    tbl_rel_tesserato_discipline_societa.idtbl_rel_tesserato_discipline
    LEFT JOIN tbl_discipline_praticate ON tbl_discipline_praticate.idtbl_disciplina_praticate=tbl_rel_tesserato_discipline_praticate.disciplina_praticata_id
    WHERE
    tbl_tesserati.cognome LIKE ?
    AND tbl_tesserati.nome LIKE ?
    AND tbl_rel_tesserato_discipline_societa.id_societa LIKE ?
    AND tbl_tesserati.idtbl_tesserati LIKE ?
    AND tbl_cariche.idtbl_cariche LIKE ?
    AND tbl_qualifiche.idtbl_qualifiche LIKE ?
    AND tbl_tesserati.data_nascita >= ?
    AND tbl_tesserati.data_nascita<= ?
    AND tbl_discipline.idtbl_discipline LIKE ?
    AND codice_affiliazione LIKE ?
    AND tbl_societa.denominazione LIKE ?
    AND YEAR(tbl_rel_tesserato_discipline_societa.data_scadenza) LIKE ?
    AND (tbl_province.nome LIKE ? OR tbl_province.nome IS NULL)
    AND ( tbl_comuni.nome LIKE ? OR tbl_comuni.nome IS NULL)
    The tbl_tesserati.data_nascita is a mysql date field.
    The click event handler code for the "Details" Button is:
    public String btnModificaTesserato_action() {
            try{
                TableRowDataProvider rowData= (TableRowDataProvider)getBean("currentRowTesserati");
                getRequestBean1().setId_tesserato((Long)rowData.getValue("idTesserato"));          
            } catch(Exception ex) {
                log("errore nella query",ex);
            return "dettaglioTesseratoSocieta";
        }When i run the project and open the page the table is correctly rendered and populated with some rows. But when i click on details button nothing happens, the page is simply reloaded.
    If i set a breakpoint in the code line   TableRowDataProvider rowData= (TableRowDataProvider)getBean("currentRowTesserati");the debbuger does not stop the code execution ! As if the button was never clicked!
    I tried to modify the source query to :
    SELECT tbl_tesserati.idtbl_tesserati idTesserato,
    tbl_tesserati.num_tessera,
    tbl_tesserati.nome,
    tbl_societa.codice_meccanografico
    FROM tbl_tesserati
    INNER JOIN tbl_rel_tesserato_discipline_societa ON tbl_tesserati.idtbl_tesserati = tbl_rel_tesserato_discipline_societa.id_tesserato
    INNER JOIN tbl_cariche ON      tbl_rel_tesserato_discipline_societa.id_carica = tbl_cariche.idtbl_cariche
    INNER JOIN tbl_qualifiche ON      tbl_rel_tesserato_discipline_societa.id_qualifica = tbl_qualifiche.idtbl_qualifiche
    INNER JOIN tbl_discipline ON      tbl_rel_tesserato_discipline_societa.id_disciplina = tbl_discipline.idtbl_discipline
    INNER JOIN tbl_societa ON      tbl_rel_tesserato_discipline_societa.id_societa = tbl_societa.idtbl_societa
    LEFT JOIN tbl_province ON tbl_societa.provincia_sede_sociale = tbl_province.idtbl_province
    LEFT JOIN tbl_comuni ON tbl_societa.comune_sede_sociale = tbl_comuni.idtbl_comuni
    LEFT JOIN tbl_rel_tesserato_discipline_praticate ON tbl_rel_tesserato_discipline_praticate.tessera_id=
    tbl_rel_tesserato_discipline_societa.idtbl_rel_tesserato_discipline
    LEFT JOIN tbl_discipline_praticate ON tbl_discipline_praticate.idtbl_disciplina_praticate=tbl_rel_tesserato_discipline_praticate.disciplina_praticata_id
    WHERE
    tbl_tesserati.cognome LIKE ?
    AND tbl_tesserati.nome LIKE ?
    AND tbl_rel_tesserato_discipline_societa.id_societa LIKE ?
    AND tbl_tesserati.idtbl_tesserati LIKE ?
    AND tbl_cariche.idtbl_cariche LIKE ?
    AND tbl_qualifiche.idtbl_qualifiche LIKE ?
    AND tbl_tesserati.data_nascita >= ?
    OR tbl_tesserati.data_nascita<= ?
    AND tbl_discipline.idtbl_discipline LIKE ?
    AND codice_affiliazione LIKE ?
    AND tbl_societa.denominazione LIKE ?
    AND YEAR(tbl_rel_tesserato_discipline_societa.data_scadenza) LIKE ?
    AND (tbl_province.nome LIKE ? OR tbl_province.nome IS NULL)
    AND ( tbl_comuni.nome LIKE ? OR tbl_comuni.nome IS NULL)
    Using this query everything works well !! The click handler works and the debugger too !!
    I changed only the AND in OR !!!
    I also tried to change mysql-x-x-connector driver but without solving my problem.
    Can someone help me ?
    Thanks
    Giorgio

    You'll find that it is more to do with the way MySql deals with dates than anything else! Depending on how your date field is setup, then try using a BETWEEN statement for those 2 lines in your first query e.g.
    AND ( tbl_tesserati.data_nascita BETWEEN ? AND ?)
    The date column needs to be in the ISO format to work. If you examine your second query output, you might discover that the output is only going to refer to one parameter (probably the OR one). Did you manage to view the output logs from the application server? You would have got an idea from there with a message like stating a conversion error'.
    Alternatively, you could try using the to_days() function and convert it directly to a number which would be a lot easier to deal with. For example:
    AND to_days(tbl_tesserati.data_nascita >= ? )
    AND to_days( tbl_tesserati.data_nascita<= ? )
    Or try the BETWEEN version with to_days() and see what you get.
    More info about date formatting (v5) here:
    http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_to-days
    Before I forget, sometimes you may need to treat dates as Strings rather 'Long' as you did.
    As a matter of interest, did you try your query in a different piece of software?
    If my queries are a little more complicated, I tend to try MySql queries out in the free MySql query browser and also double check in another to verify certain issues. I found it easier to develop SQL in a seperate program then import the final version to JSC making the required modifications for parameters.
    Message was edited by:
    aerostra

  • Help with SQL query

    Hi all,
    I need the last run date of each Discoverer report with the user name of who created the report. The following SQL does this, but the Last_Run date shows the same for each report which is wrong. If I run the SQL that shows me the last run date of each report it does show the correcct last run date. But when I add the extra code to sow me the user who created the report it goes wrong.
    I am running the query in Toad:
    SELECT DISTINCT
    *(SELECT TRUNC(MAX(DM.QS_CREATED_DATE))*
    FROM
    EUL9I.EUL5_QPP_STATS DM,
    EUL9I.EUL5_QPP_STATS STATS
    WHERE DM.QS_DOC_NAME = STATS.QS_DOC_NAME) LAST_RUN, Disco_Docs.Doc_Name "Discoverer Workbook"
    ,Trunc(Disco_Docs.Doc_Created_Date) "Workbook Create Date"
    ,CASE
    WHEN Instr(Disco_Docs.Doc_Created_By
    ,'#') = 0 THEN
    Disco_Docs.Doc_Created_By
    WHEN Instr(Disco_Docs.Doc_Created_By
    ,'#') > 0
    AND Instr(Disco_Docs.Doc_Created_By
    ,2) = 0 THEN
    (SELECT Fu.User_Name
    FROM Fnd_User Fu
    WHERE Fu.User_Id = Substr(Disco_Docs.Doc_Created_By
    ,2
    ,5))
    ELSE
    NULL
    END "Workbook Owner/Creator"
    FROM EUL9I.Eul5_Documents Disco_Docs
    ,EUL9I.Eul5_Access_Privs Disco_Shares
    ,EUL9I.Eul5_Eul_Users Disco_Users
    WHERE Disco_Docs.Doc_Id = Disco_Shares.Gd_Doc_Id(+) AND
    Disco_Users.Eu_Username(+) NOT IN ('EUL5', 'PUBLIC') AND
    Disco_Users.Eu_Id(+) = Disco_Shares.Ap_Eu_Id

    Your code formatted for readability...
    SELECT DISTINCT
          (SELECT TRUNC(MAX(DM.QS_CREATED_DATE))
           FROM   EUL9I.EUL5_QPP_STATS DM,
                  EUL9I.EUL5_QPP_STATS STATS
           WHERE  DM.QS_DOC_NAME = STATS.QS_DOC_NAME) LAST_RUN
          ,Disco_Docs.Doc_Name "Discoverer Workbook"
          ,Trunc(Disco_Docs.Doc_Created_Date) "Workbook Create Date"
          ,CASE WHEN Instr(Disco_Docs.Doc_Created_By,'#') = 0 THEN
                  Disco_Docs.Doc_Created_By
                WHEN Instr(Disco_Docs.Doc_Created_By,'#') > 0 AND Instr(Disco_Docs.Doc_Created_By,'#',2) = 0 THEN
                  (SELECT Fu.User_Name
                   FROM   Fnd_User Fu
                   WHERE  Fu.User_Id = Substr(Disco_Docs.Doc_Created_By,2,5))
                ELSE
                  NULL
           END "Workbook Owner/Creator"
    FROM   EUL9I.Eul5_Documents Disco_Docs
          ,EUL9I.Eul5_Access_Privs Disco_Shares
          ,EUL9I.Eul5_Eul_Users Disco_Users
    WHERE  Disco_Docs.Doc_Id = Disco_Shares.Gd_Doc_Id(+)
    AND    Disco_Users.Eu_Username(+) NOT IN ('EUL5', 'PUBLIC')
    AND    Disco_Users.Eu_Id(+) = Disco_Shares.Ap_Eu_IdThe code you've added (I assume that's the bit you bolded ) queries the same value for each row it returns. It's not tied into the main query in any way, so of course it will always return the same.

  • Help with MYSQLi Query and WHILE statement

    Hi,
    Not sure what is wrong here but the same record is printed in the while loop 11 times (the amount of records in the table).
    <?php 
    //Main Connection & Query
    //Database Connection & Error
    $con_host = 'X';
    $con_username = 'X';
    $con_password = 'X';
    $con_database = 'X';
    $con = mysqli_connect($con_host, $con_username, $con_password, $con_database);
    ?>
    <?php
    //Query
    $sql = "SELECT * FROM equipment ORDER BY name ASC";
    $query = mysqli_query($con, $sql);
    $row = mysqli_fetch_assoc($query);
    $row_count = mysqli_num_rows($query);
    //Create Variables
    $name = $row['name'];
    $size = $row['size'];
    $quantity = $row['quantity'];
    $protection = $row['protection'];
    $location = $row['location'];
    $sublocation = $row['sublocation'];
    $bc = $row['BC'];
    $id = $row['id'];
    ?>
    <!doctype html>
    <html>
    <link href="stylesheets/main_stylesheet.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
    <!-- Favicon -->
    <link rel="shortcut icon" type="image/png" href="images/icon.png" />
    <style type="text/css">
    </style>
    <head>
    <meta charset="utf-8">
    <title>Print Equipment List</title>
    <link href="stylesheets/print_stylesheet.css" rel="stylesheet" type="text/css">
    <script src="sorttable.js"></script>
    <!--<body onload="window.print()">-->
    </head>
    <body>
    <div class="print_button no-print" onClick="window.print()">Print</div>
    <div class="print_text no-print">Select the sorting of the list by clicking on the table categories and click the print button below</div>
    <div class="print_a4page">
      <div class="print_header">
         <div class="print_header_logo"><img src="images/logo.png" width="306" height="43"></div>
          <div class="print_header_text" id="header_text">Drama Database</div>
          <div class="print_header_info">List printed: <script type="text/javascript">
      var currentTime = new Date();
      var month = currentTime.getMonth() + 1;
      var day = currentTime.getDate();
      var year = currentTime.getFullYear();
      document.write(day + "/" + month + "/" + year);</script>
      <br>
    Total records:
    <?php echo $row_count ?></div>
      </div>
        <div class="print_header_divider">Equipment List</div>
        <div class="print_body">
          <div>
            <form name="users" method="post">
              <div class="table_print">
              <table width="100%" border="0" cellpadding="5" class="sortable">
                <tr class="table_header_print">
                  <th width="15%" scope="col">Name</th>
                  <th width="12%" scope="col">Size</th>
                  <th width="9%" scope="col">Quantity</th>
                  <th width="12%" scope="col">Protection</th>
                  <th width="17%" scope="col">Location</th>
                  <th width="12%" scope="col">Sublocation</th>
                  <th width="11%" scope="col">Barcode</th>
                  <th width="12%" scope="col">Internal ID</th>
                </tr>
                <?php do { ?>
                <tr class="table_body">
                  <td><?php echo $name ?></td>
                  <td><?php echo $size ?></td>
                  <td><?php echo $quantity ?></td>
                  <td><?php echo $protection ?></td>
                  <td><?php echo $location ?></td>
                  <td><?php echo $sublocation ?></td>
                  <td><?php echo $bc ?></td>
                  <td><?php echo $id ?></td>
                </tr>
                <?php } while ($row = mysqli_fetch_assoc($query));?>
              </table>
            </form>
          </div>
        </div>
    </div>
    </body>
    </html>

    Still getting the same issue.
    As I see it, the way you have suggested is just rearanging things right?
    here is a screenshot of the outcome:
    And here is the improved code:
    <?php 
    //Main Connection & Query
    //Database Connection & Error
    $con_host = 'X';
    $con_username = 'X';
    $con_password = 'X';
    $con_database = 'X';
    $con = new mysqli($con_host, $con_username, $con_password, $con_database);
    ?>
    <?php
    //Query
    $sql = "SELECT * FROM equipment ORDER BY name ASC";
    $result = $con->query($sql);
    $row = $result->fetch_assoc();
    $row_count = $result->num_rows;
    //Create Variables
    $name = $row['name'];
    $size = $row['size'];
    $quantity = $row['quantity'];
    $protection = $row['protection'];
    $location = $row['location'];
    $sublocation = $row['sublocation'];
    $bc = $row['BC'];
    $id = $row['id'];
    ?>
    <!doctype html>
    <html>
    <link href="stylesheets/main_stylesheet.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
    <!-- Favicon -->
    <link rel="shortcut icon" type="image/png" href="images/icon.png" />
    <style type="text/css">
    </style>
    <head>
    <meta charset="utf-8">
    <title>Print Equipment List</title>
    <link href="stylesheets/print_stylesheet.css" rel="stylesheet" type="text/css">
    <script src="sorttable.js"></script>
    <!--<body onload="window.print()">-->
    </head>
    <body>
    <div class="print_button no-print" onClick="window.print()">Print</div>
    <div class="print_text no-print">Select the sorting of the list by clicking on the table categories and click the print button below</div>
    <div class="print_a4page">
      <div class="print_header">
         <div class="print_header_logo"><img src="images/logo.png" width="306" height="43"></div>
          <div class="print_header_text" id="header_text">Drama Database</div>
          <div class="print_header_info">List printed: <script type="text/javascript">
      var currentTime = new Date();
      var month = currentTime.getMonth() + 1;
      var day = currentTime.getDate();
      var year = currentTime.getFullYear();
      document.write(day + "/" + month + "/" + year);</script>
      <br>
    Total records:
    <?php echo $row_count ?></div>
      </div>
        <div class="print_header_divider">Equipment List</div>
        <div class="print_body">
          <div>
            <form name="users" method="post">
              <div class="table_print">
              <table width="100%" border="0" cellpadding="5" class="sortable">
                <tr class="table_header_print">
                  <th width="15%" scope="col">Name</th>
                  <th width="12%" scope="col">Size</th>
                  <th width="9%" scope="col">Quantity</th>
                  <th width="12%" scope="col">Protection</th>
                  <th width="17%" scope="col">Location</th>
                  <th width="12%" scope="col">Sublocation</th>
                  <th width="11%" scope="col">Barcode</th>
                  <th width="12%" scope="col">Internal ID</th>
                </tr>
                <?php while ($row = $result->fetch_assoc()) { ?>
                <tr class="table_body">
                  <td><?php echo $name ?></td>
                  <td><?php echo $size ?></td>
                  <td><?php echo $quantity ?></td>
                  <td><?php echo $protection ?></td>
                  <td><?php echo $location ?></td>
                  <td><?php echo $sublocation ?></td>
                  <td><?php echo $bc ?></td>
                  <td><?php echo $id ?></td>
                </tr>
                <?php } ?>
              </table>
            </form>
          </div>
        </div>
    </div>
    </body>
    </html>

  • Help with LAG () OVER () and dates

    I have the following query right now
      SELECT "DATE",
              "CELL_SITE",
              "LASTV_ATTCNT",
              "LASTV_ATTCNT2",
              "LASTV_BLKCNT",
              "LASTV_DRPCNT",
              "V_ATT_CNT",
              "V_CUST_BLK_CNT",
              "V_DRP_CALL_CNT",
              "LASTD_ATTCNT",
              "LASTD_BLKCNT",
              "LASTD_DRPCNT",
              "D_ATT_CNT",
              "D_CUST_BLK_CNT",
              "D_DRP_CALL_CNT"         
         FROM (  SELECT DATE,
                       CELL_SITE,
                        LAG (SUM (V_ATT_CNT), 24)
                           OVER (PARTITION BY BSM_NM ORDER BY DATE)
                           AS "LASTV_ATTCNT",
                        LAG (SUM (V_CUST_BLK_CNT), 24)
                           OVER (PARTITION BY BSM_NM ORDER BY DATE)
                           AS "LASTV_BLKCNT",
                        LAG (SUM (V_DRP_CALL_CNT), 24)
                           OVER (PARTITION BY BSM_NM ORDER BY DATE)
                           AS "LASTV_DRPCNT",
                        LAG (SUM (D_ATT_CNT), 24)
                           OVER (PARTITION BY BSM_NM ORDER BY DATE)
                           AS "LASTD_ATTCNT",
                        LAG (SUM (D_CUST_BLK_CNT), 24)
                           OVER (PARTITION BY BSM_NM ORDER BY DATE)
                           AS "LASTD_BLKCNT",
                        LAG (SUM (D_DRP_CALL_CNT), 24)
                           OVER (PARTITION BY BSM_NM ORDER BY DATE)
                           AS "LASTD_DRPCNT",
                        SUM (V_ATT_CNT) AS "V_ATT_CNT",
                        SUM (V_CUST_BLK_CNT) AS "V_CUST_BLK_CNT",
                        SUM (V_DRP_CALL_CNT) AS "V_DRP_CALL_CNT",
                        SUM (D_ATT_CNT) AS "D_ATT_CNT",
                        SUM (D_CUST_BLK_CNT) AS "D_CUST_BLK_CNT",
                        SUM (D_DRP_CALL_CNT) AS "D_DRP_CALL_CNT"
                   FROM DMSN.DS3R_FH_1XRTT_FA_LVL_KPI
                  WHERE DATE >
                             (SELECT MAX (DATE) FROM DMSN.DS3R_FH_1XRTT_FA_LVL_KPI)
                           - 2
               GROUP BY DATE, CELL_SITE)
        WHERE DATE >=
                 (SELECT MAX (DATE) - NUMTODSINTERVAL (12, 'HOUR')
                    FROM DMSN.DS3R_FH_1XRTT_FA_LVL_KPI)What I've noticed is that the LAG function is doing kind of what I want but not exactly. Lets say I have data for hours 12AM, 1AM, 2AM, 3AM, 4AM, 5AM, 6AM, 7AM, 8AM, 9AM, 10AM, 11AM, 12PM, and that the current hour is 12PM, the LAG function goes back to 12AM, which is what it should be doing.
    but lets say I have data for 12AM, 1AM, 2AM, 3AM, 4AM, 5AM, 7AM, 8AM, 9AM, 10AM, 11AM, 12PM, but am MISSING 6AM (no data for 6AM). The lag function will now go back to 11PM instead of 12AM since the 6AM hour is missing.
    if I have data for 12AM, 1AM, 2AM, 3AM, 4AM, 7AM, 8AM, 9AM, 10AM, 11AM, 12PM and am MISSING 5AM and 6AM, the data will go back to 10PM then and not just 12AM.
    Can I prevent this from happening and always just go back 12 hours?
    Edited by: k1ng87 on Apr 25, 2013 1:27 PM

    Hi,
    k1ng87 wrote:
    LAG (SUM (V_ATT_CNT), 24)
    OVER (PARTITION BY BSM_NM ORDER BY DATE)
    AS "LASTV_ATTCNT",
    LAG (SUM (V_CUST_BLK_CNT), 24)
    OVER (PARTITION BY BSM_NM ORDER BY DATE)
    AS "LASTV_BLKCNT",
    LAG (SUM (V_DRP_CALL_CNT), 24)
    OVER (PARTITION BY BSM_NM ORDER BY DATE)
    AS "LASTV_DRPCNT",
    Since you want so many columns from the same previous row, it would probably be simpler and more efficient to do a self-join, rather than so many LAG functions.
    What I've noticed is that the LAG function is doing kind of what I want but not exactly. Lets say I have data for hours 12AM, 1AM, 2AM, 3AM, 4AM, 5AM, 6AM, 7AM, 8AM, 9AM, 10AM, 11AM, 12PM, and that the current hour is 12PM, the LAG function goes back to 12AM, which is what it should be doing.You're always passing 24 as the 2nd argument to LAG; that means "Return the value from the 24th precding row." If there's a row for every hour, and the current row is 12PM, then wouldn't 24 rows back would be 12PM yesterday, not 12AM? Maybe you meant to pass 12, not 24, as the second argument to LAG. I'll assume you really want the 24th row rom now on, but the technique is the same whether that number is 24 or 12.
    but lets say I have data for 12AM, 1AM, 2AM, 3AM, 4AM, 5AM, 7AM, 8AM, 9AM, 10AM, 11AM, 12PM, but am MISSING 6AM (no data for 6AM). The lag function will now go back to 11PM instead of 12AM since the 6AM hour is missing.
    if I have data for 12AM, 1AM, 2AM, 3AM, 4AM, 7AM, 8AM, 9AM, 10AM, 11AM, 12PM and am MISSING 5AM and 6AM, the data will go back to 10PM then and not just 12AM.
    Can I prevent this from happening and always just go back 12 hours?A self-join would handle this automatically: it will look for the matching row, without regard for which other rows might be present or absent.
    If you really had to do this with analytic functions, you could use MIN or FIRST_VALUE with a range window:
    RANGE BETWEEN  1 + (.5 / 24)  PRECEDING
          AND      1 - (.5 / 24)  PRECEDINGWhen you ORDER BY a DATE column (don't call it "DATE"), the units are 1 day, so 1+(.5/24) days ago is 24.5 hours ago; that is, the window only includes DATES between 24.5 and 23.5 hours ago.
    If, for some reason, you really wanted to call LAG, then you could do an outer join to guarantee that a row was present for each of the preceding 24 hours.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

Maybe you are looking for

  • Unable to run SSIS Package using Stored Procedure

    Hi Guys,         I have create one simple SSIS Package(Move the first table record to second table).It will execute fine in locally. But, If i'm going call/execute .dtsx file using stored procedure. I'm getting Error. so please let me know the valuab

  • PDF generation in SDK

    All, I have some reports, whose PDF generation doesn't satisfy our requirements. A simple BO report page with a few sections.. ends up as a multiple page PDF. I had tried to also use the report/section properties as creatively as possible too. I woul

  • Color correction on color

    Is anybody graded full feature film (2k or 4k)on color.How is the result?Is there will be a differnce if i use base light or lustre?Cause i am planning to use colr with a good colorist for my feature film.

  • ORA-20079:  WM internal error [unable to rename table]

    Hi, I am getting following error when i try to enable versioning on a table. Any idea how to resolve it ? BEGIN DBMS_WM.EnableVersioning('TestTable'); END; ERROR at line 1: ORA-20079: WM internal error [unable to rename table] ORA-06512: at "SYS.LTDD

  • AP12809: There is no data to display

    Hi all, owb10g R2 Created a wizard to import file definitions but unable to sample the file bcoz of this error. File is in local directory. c:\oneemployee\2122008.txt Accessed using FTP 10.1.6.28 What might be the prob? Thx in advance