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.

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.

  • 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

  • Need help with SQL Query

    I am trying to build a query that sums up 12 columns depending on some accounting variables.
    example:
    SELECT gbmcu, gbco, gbfy,'',SUM(gban01 gban02 gban03 gban04 gban05+gban06+gban07+gban08+gban09+gban10+gban11+gban12) AS Oil_Volumes
    FROM PRODDTA.F0902
    WHERE GBCO = '00099'
    AND GBFY = 5
    AND GBLT = 'QU' AND GBOBJ = 5015 AND GBSUB = '105'
    GROUP BY gbmcu, gbco, gbfy
    The condition that changes is :AND GBLT = 'QU' AND GBOBJ = 5015 AND GBSUB = '105'
    I need to do this for 17 different conditions - I need to make the query as optimized as possible.
    I tried using a case statement but that takes forever (the table is over 4 million records to scan through).
    Please let me know if anyone has any suggestions on how to create something to perform these calculations.
    thanks,
    Pam

    I think I would tend to write that query as:
    SELECT gbmcu, gbco, gbfy,
           SUM(CASE WHEN gblt = 'QA' AND gbobj = 5015 AND gbsub = '105' THEN
                    gban01+gban02+gban03+gban04+gban05+gban06+gban07+gban08+gban09+gban10+gban11+gban12 END) Oil_Sales
           SUM(CASE WHEN gblt = 'QU' AND gbobj = 5015 AND gbsub = '105' THEN
                    gban01+gban02+gban03+gban04+gban05+gban06+gban07+gban08+gban09+gban10+gban11+gban12 END) Oil_Volumes
    FROM proddta.f0902
    WHERE gbco = '00099' and
          gbfy = 5 and
          gblt IN ('QA', 'QU') and
          gbpbj = 5015 and
          gbsub = '105'
    GROUP BY gbmcu, gbco, gbfySUM the CASE rather than CASE SUM. Also, as written, your query will look at all of the records in f0902 whether or not they meet one of the Case criteria, so I would put the required values in the WHERE clause as well. Your samples only show gblt changing, so you may need to make the gbpbj and gbsub predicates IN lists as well.
    If the query runs in 1.5 hours calculating one value, I would expect it to be about the same calculating 17 values, since I would bet that most of the run time is accessing the table rather than doing the math. It would almost certainly be faster than running essentially the same query 17 times.
    Indexes on some or all of the columns in the WHERE clause may help, depending on how selective the columns are. At a guess, I would suggest that gbco and gbfy would be good candidates.
    Finally, are you sure that gbsub is a character field? The only example we have is a number.
    HTH
    John

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

  • 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

    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.

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

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

  • Help with sql query for multiple years

    Hello,
    I am new to SQL and am trying to perform a query that includes multiple years from 2005 to 2011.
    I was trying to enter the following query but received a message that said "Operand should contain 1 column(s)"
    SELECT * FROM `auto_2` WHERE `year` LIKE (2005, 2006, 2007, 2008, 2009, 2010, 2011);
    What am I doing wrong here? Please advise...
    Thanks

    Hi and welcome to the forum,
    You cannot use LIKE here, that is for pattern matching.
    You need either IN operator, or less known =ANY.
    Regards
    Peter

  • Help with a query regarding time dependent display of Plan/Actual data

    Hello,
    Let me try to explain what my problem is:
    I have a query that shows plan and actual sales figures on a timeline. Plan and actual data is identified by 0VERSION (P01 for Plan; P00 for Actual).
    0CALMONTH and Sales key figure is in rows. 0VERSION is in collums.
    The output looks as follows (simplified):
    CalYYYY/MM............P01....P00
    2006.09......Sales........90.....100
    2006.10......Sales......100.......95
    2006.11......Sales........90........0
    2006.12......Sales........95........0
    So far so good! But users aren't satisfied with that. They want only <u>one</u> collumn with sales figures. For past months (< 2006.11) they want to see actual figures (Version P00). For current and future month (>= 2006.11) they want to see plan figures (Version P01). And this only in one single collumn.
    So the output should look this way:
    CalYYYY/MM..........P00/P01
    2006.09......Sales......100
    2006.10......Sales.... ...95
    2006.11......Sales........90
    2006.12......Sales........95
    Is there any way/workaround to accomplish this?
    Your help will be very appreciated!
    Regards,
    Ulrich

    Hi,
    For this what you can try is , have the two Restricted Key Figs the way you have right now, but Hide them. Then Create a Third Formula Key Fig, in which you can put a Boolean Logic :
    (FV > 11) * Act KF +(FV<= 11)*Plan KF
    Where FV is a Formula Variable which takes on the Value from Month (1 for Jan , 2 for Feb etc)
    Try something on these lines.

  • Help with SQL Query Involving Three Database Tables

    Hi,
    My SQL is very rusty since I have not touched it in over one year.
    I was given an SQL question in a job interview and I am curious to know the right answer.
    This was a pre-prepared written test and the interviewer did not know the answer.
    There are three database tables: STUDENTS, COURSES and STUDENT_COURSES
    Table STUDENTS has STUDENT_ID and STUDENT_NAME columns.
    Table COURSES has COURSE_ID and COURSE_DESCRIPTION columns.
    Table STUDENT_COURSES has columns STUDENT_ID and COURSE_ID.
    Provide a query that returns all the students that are enrolled in all the courses.
    Thanks,
    Avi.

    It is probably good to say that this task may be solved such way, if database normalized and there are references
    Basically here just is a variant of your solution
    DROP TABLE student_course;
    DROP TABLE student;
    DROP TABLE course;
    CREATE TABLE student
    (student_id NUMBER(9) PRIMARY KEY,
    student_name VARCHAR2(30));
    CREATE TABLE course
    (course_id NUMBER(9) PRIMARY KEY,
    dscr VARCHAR2(100));
    CREATE TABLE student_course
    (student_id NUMBER(9),
    course_id NUMBER(9));
    ALTER TABLE student_course
    ADD CONSTRAINT pk_st_crs PRIMARY KEY
    (student_id, course_id);
    ALTER TABLE student_course
    ADD CONSTRAINT fk_student
      FOREIGN KEY (student_id)
      REFERENCES student(student_id);
    ALTER TABLE student_course
    ADD CONSTRAINT fk_course
      FOREIGN KEY (course_id)
      REFERENCES course(course_id);
    INSERT INTO student
         VALUES (1, 'NAME1');
    INSERT INTO student
         VALUES (2, 'NAME2');
    INSERT INTO student
         VALUES (3, 'NAME3');
    INSERT INTO course
         VALUES (101, 'Desc 1');
    INSERT INTO course
         VALUES (102, 'Desc 2');
    INSERT INTO course
         VALUES (103, 'Desc 3');
    INSERT INTO student_course
         VALUES (1, 101);
    INSERT INTO student_course
         VALUES (1, 102);
    INSERT INTO student_course
         VALUES (2, 101);
    INSERT INTO student_course
         VALUES (2, 103);
    INSERT INTO student_course
         VALUES (3, 101);
    INSERT INTO student_course
         VALUES (3, 102);
    INSERT INTO student_course
         VALUES (3, 103);
    COMMIT ;
    WITH st_crs_cnt AS
         (SELECT   student_id,
                   COUNT (*) tot
              FROM student_course
          GROUP BY student_id)
    SELECT sc.student_id,
           sc.tot
      FROM st_crs_cnt sc
      WHERE sc.tot = (SELECT COUNT (*) FROM course);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Help with sql query on materialized view logs

    I am in need of a query to find out what tablespace and snap shot site a long list of materialized view logs are associated with.
    something like below except tablespace and snap_shot_site are not an option for this table.
    select log_owner, master, log_table, tablespace, snap_shot_site from dba_mview_logs;

    What is the refresh method set as?
    Could you paste the full MV log creation script and the corresponding MV creation script.

  • 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()

Maybe you are looking for

  • Automatic Clearing without any criteria

    Hi Seniors, My Client wants to clear two GL accounts by just matching Debit and Credit without any criteria.  I mean when we try to do automatic clearing system proposes to clear based on the criteria given in customizing.  But, as per automatic clea

  • READ SCALES  IN   PURCHASE ORDER

    HELLO. I WANT TO READ THE    SCALES       DATA FOR A PURCHASE ORDER. ITS THE DATA WHICH SHOWS DIFFERENT PRICES FROM VENDOR WHEN YOU PURCHASE DIFFERENT  QUANTITY  OF MATERIAL. IS THERE ANY ABAP FUNCTION FOR THIS ? THANKS

  • How do I unlock folders for drag/drop messages?

    Team: I have 2 folders in Thunderbird that will not allow me to drag/drop messages into it. I was able to do this up to about a week ago and now I can't drag/drop. I have restarted in safe mode but it didn't release the folders for drag/drop. I've ch

  • CIN - Depot Sales and Export Sales

    hi all i have few queries assosiated with cin 1. Depot Sales Process:  As Depot sales pricing procedure will not have excise condition types in that, how we are going to pass the excise amounts to our customers so that they can take the excise credit

  • Migration from DPL to Base API, is it possible ?

    Hello, Once developing an application using the DPL, will it be possible to migrate to the Base API (for example if we need to use JCA or JMX later) ? Is there a project or future development to use JCA or JMX over DPL DB ? Thanks Fahmi