Sql query to calculate order completion time

Hello,
This is probably a textbook example, but I was wondering if someone could show me the technique to answer the following question based on the sample data:
Show all orders from the orders table where completion time (defined as difference between time the order was completed and received). is > 5 hours
Order_id
Action
Time
1
Received
1/11/2014 10:12:00
1
Logged
1/11/2014 10:15:00
1
Sent
1/11/2014 15:15:00
1
Complete
1/11/2014 16:15:00
2
Received
31/10/2014 8:10
2
Logged
31/10/2014 8:28
2
Sent
31/10/2014 10:11
2
Complete
31/10/2014 12:13
3
Received
30/10/2014 13:10
3
Logged
30/10/2014 15:10
3
Sent
30/10/2014 16:10
3
Complete
30/10/2014 17:10
Thanks

create table orders (order_id int, action varchar(50), [time] datetime)
insert into orders values(1,'Received','1/11/2014 10:12'),(1,'Logged','1/11/2014 10:15'),(1,'Sent','1/11/2014 15:15'),(1,'Complete','1/11/2014 16:15'),
(2,'Received','10/31/2014 08:10'),(2,'Logged','10/31/2014 08:28'),(2,'Sent','10/31/2014 10:11'),(2,'Complete','10/31/2014 12:13'),
(3,'Received','10/30/2014 13:10'),(3,'Logged','10/30/2014 15:10'),(3,'Sent','10/30/2014 16:10'),(3,'Complete','10/30/2014 17:10')
select order_id from (
select *, datediff(hour,lag([time],1) Over(partition by order_id Order by [time]),[time]) diff
from orders WHERE action IN ('Complete','Received')) t
WHERE diff>=5
drop table orders

Similar Messages

  • SQL Query to calculate on-time dispatch with a calendar table

    Hi Guys,
    I have a query (view) to calculate orders' fulfillment leadtimes.
    The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name
    isBusinessDay but I don't know how to best use this table to calculate the On-Time metric. I have been looking everywhere but so far I have been unable to solve my problem.
    Please find below the current calculation for the On-Time Column:
    SELECT
    Week#
    , ClntGroup
    , CORD_DocumentCode
    , DESP_DocumentCode
    , Cord_Lines --#lines ordered
    , CORD_Qty --total units orderd
    , DESP_Lines --#lines dispatched
    , DESP_Qty --total units dispatched
    , Status
    , d_status
    , OpenDate --order open date
    , DateDue
    , DESP_PostedDate --order dispatched date
    , DocType
    , [Lead times1]
    , [Lead times2]
    , InFxO
    , OnTime
    , InFxO + OnTime AS InFullAndOneTime
    , SLADue
    FROM (
    SELECT
    DATEPART(WEEK, d.DateOpn) AS Week#
    , Clients.CustCateg
    , Clients.ClntGroup
    , d.DocumentCode AS CORD_DocumentCode
    , CDSPDocs.DocumentCode AS DESP_DocumentCode
    , COUNT(CORDLines.Qnty) AS Cord_Lines
    , SUM(CORDLines.Qnty) AS CORD_Qty
    , COUNT(CDSPLines.Qnty) AS DESP_Lines
    , SUM(CDSPLines.Qnty) AS DESP_Qty
    , CDSPLines.Status
    , d.Status AS d_status
    , d.OpenDate
    , d.DateDue
    , CDSPDocs.PostDate AS DESP_PostedDate
    , d.DocType
    , DATEDIFF(DAY, d.OpenDate, d.DateDue) AS [Lead times1]
    , DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) AS [Lead times2]
    , CASE WHEN SUM(CORDLines.Qnty) = SUM(CDSPLines.Qnty) THEN 1 ELSE 0 END AS InFxO --in-full
    --On-Time by order according to Despatch SLAs
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales', 'Mail Order')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2 ) <= 2)
    THEN 1
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - USA')
    AND (DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate) - (DATEDIFF(WEEK, d.OpenDate, CDSPDocs.PostDate) * 2) <= 14)
    THEN 1
    WHEN Clients.ClntGroup = 'Export Market' OR Clients.CustCateg = 'UK Transfer'
    AND d.DateDue >= CDSPDocs.PostDate
    THEN 1
    ELSE 0
    END AS OnTime
    --SLA Due (as a control)
    , CASE
    WHEN Clients.ClntGroup IN ('Local Market', 'Web Sales','Mail Order') AND CDSPDocs.PostDate is Null
    THEN DATEADD(DAY, 2 , d.OpenDate)
    WHEN Clients.ClntGroup IN ('Export Market', 'Export Market - UK', 'Export Market - USA') OR (Clients.CustCateg = 'UK Transfer')
    AND CDSPDocs.PostDate IS NULL
    THEN DATEADD (DAY, 14 , d.OpenDate)
    ELSE CDSPDocs.PostDate
    END AS SLADue
    FROM dbo.Documents AS d
    INNER JOIN dbo.Clients
    ON d.ObjectID = dbo.Clients.ClntID
    AND Clients.ClientName NOT in ('Samples - Free / Give-aways')
    LEFT OUTER JOIN dbo.DocumentsLines AS CORDLines
    ON d.DocID = CORDLines.DocID
    AND CORDLines.TrnType = 'L'
    LEFT OUTER JOIN dbo.DocumentsLines AS CDSPLines
    ON CORDLines.TranID = CDSPLines.SourceID
    AND CDSPLines.TrnType = 'L'
    AND (CDSPLines.Status = 'Posted' OR CDSPLines.Status = 'Closed')
    LEFT OUTER JOIN dbo.Documents AS CDSPDocs
    ON CDSPLines.DocID = CDSPDocs.DocID
    LEFT OUTER JOIN DimDate
    ON dimdate.[Date] = d.OpenDate
    WHERE
    d.DocType IN ('CASW', 'CORD', 'MORD')
    AND CORDLines.LneType NOT IN ('Fght', 'MANF', 'Stor','PACK', 'EXPS')
    AND CORDLines.LneType IS NOT NULL
    AND d.DateDue <= CONVERT(date, GETDATE(), 101)
    GROUP BY
    d.DateOpn
    ,d.DocumentCode
    ,Clients.CustCateg
    ,CDSPDocs.DocumentCode
    ,d.Status
    ,d.DocType
    ,d.OpenDate
    ,d.DateReq
    ,CDSPDocs.PostDate
    ,CDSPLines.Status
    ,Clients.ClntGroup
    ,d.DocumentName
    ,d.DateDue
    ,d.DateOpn
    ) AS derived_table
    Please find below the DimDate table
    FullDateNZ HolidayNZ IsHolidayNZ IsBusinessDay
    24/12/2014 NULL 0 1
    25/12/2014 Christmas Day 1 0
    26/12/2014 Boxing Day 1 0
    27/12/2014 NULL 0 0
    28/12/2014 NULL 0 0
    29/12/2014 NULL 0 1
    30/12/2014 NULL 0 1
    31/12/2014 NULL 0 1
    1/01/2015 New Year's Day 1 0
    2/01/2015 Day after New Year's 1 0
    3/01/2015 NULL 0 0
    4/01/2015 NULL 0 0
    5/01/2015 NULL 0 1
    6/01/2015 NULL 0 1
    This is what I get from the query:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 0
    52 Web Sales 123457 24/12/2014 30/12/2014 0
    52 Web Sales 123458 24/12/2014 29/12/2014 0
    52 Local Market 123459 24/12/2014 29/12/2014 0
    1 Web Sale 123460 31/12/2014 5/01/2015 0
    1 Local Market 123461 31/12/2014 6/01/2015 0
    As the difference between the dispatched and open date is 2 business days or less, the result I expect is this:
    Week# ClntGroup CORD_DocumentCode OpenDate DESP_PostedDate OnTime
    52 Web Sales 123456 24/12/2014 29/12/2014 1
    52 Web Sales 123457 24/12/2014 30/12/2014 1
    52 Web Sales 123458 24/12/2014 29/12/2014 1
    52 Local Market 123459 24/12/2014 29/12/2014 1
    1 Web Sale 123460 31/12/2014 5/01/2015 1
    1 Local Market 123461 31/12/2014 6/01/2015 1
    I am using SQL Server 2012
    Thanks
    Eric

    >> The current criteria exclude week-ends but not bank holidays therefore I have created a calendar table with a column name “isBusinessDay” but I don't know how to best use this table to calculate the On-Time metric. <<
    The Julian business day is a good trick. Number the days from whenever your calendar starts and repeat a number for a weekend or company holiday.
    CREATE TABLE Calendar
    (cal__date date NOT NULL PRIMARY KEY, 
     julian_business_nbr INTEGER NOT NULL, 
    INSERT INTO Calendar 
    VALUES ('2007-04-05', 42), 
     ('2007-04-06', 43), -- good Friday 
     ('2007-04-07', 43), 
     ('2007-04-08', 43), -- Easter Sunday 
     ('2007-04-09', 44), 
     ('2007-04-10', 45); --Tuesday
    To compute the business days from Thursday of this week to next
     Tuesdays:
    SELECT (C2.julian_business_nbr - C1.julian_business_nbr)
     FROM Calendar AS C1, Calendar AS C2
     WHERE C1.cal__date = '2007-04-05',
     AND C2.cal__date = '2007-04-10'; 
    We do not use flags in SQL; that was assembly language. I see from your code that you are still in a 1960's mindset. You used camelCase for a column name! It makes the eyes jump and screws up maintaining code; read the literature. 
    The “#” is illegal in ANSI/ISO Standard SQL and most other ISO Standards. You are writing 1970's Sybase dialect SQL! The rest of the code is a mess. 
    The one column per line, flush left and leading comma layout tells me you used punch cards when you were learning programming; me too! We did wrote that crap because a card had only 80 columns and uppercase only IBM 027 character sets. STOP IT, it make you
    look stupid in 2015. 
    You should follow ISO-11179 rules for naming data elements. You failed. You believe that “status” is a precise, context independent data element name! NO! 
    You should follow ISO-8601 rules for displaying temporal data. But you used a horrible local dialect. WHY?? The “yyyy-mm-dd” is the only format in ANSI/ISO Standard SQL. And it is one of the most common standards embedded in ISO standards. Then you used crap
    like “6/01/2015” which is varying length and ambiguous that might be “2015-06-01” or “2015-01-06” as well as not using dashes. 
    We need to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. 
    And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> Please find below the current calculation for the On-Time Column: <<
    “No matter how far you have gone down the wrong road, turn around”
     -- Turkish proverb
    Can you throw out this mess and start over? If you do not, then be ready to have performance got to hell? You will have no maintainable code that has to be kludged like you are doing now? In a good schema an OUTER JOIN is rare, but you have more of them in
    ONE statement than I have seen in entire major corporation databases.
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Problem in sql query because of order by clause

    Hi All,
    I am facing a one problem in my one sql query.I am using Oracle 10gR2.
    Query is given below:
    SELECT t1.ename
            FROM T1, T2
           WHERE T1.EMPNO = 1234
             AND T1.ACCOUNTNO = T2.ACCOUNTNO
             AND T1.SEQ = T2.SEQ
           ORDER BY T2.SEQThe Plan of the query is :
    | Id  | Operation                     | Name                 | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT              |                      |     2 |   218 | 11716   (1)| 00:00:41 |
    |*  1 |  TABLE ACCESS BY INDEX ROWID  | T1                   |     1 |    89 |     1   (0)| 00:00:01 |
    |   2 |   NESTED LOOPS                |                      |     2 |   218 | 11716   (1)| 00:00:41 |
    |*  3 |    TABLE ACCESS BY INDEX ROWID| T2                   |     2 |    40 | 11715   (1)| 00:00:41 |
    |   4 |     INDEX FULL SCAN           | PK_T2_SEQ            | 58752 |       |   122   (5)| 00:00:01 |
    |*  5 |    INDEX RANGE SCAN           | FK_ACCOUNTNO         |     3 |       |     0   (0)| 00:00:01 |
    ----------------------------------------------------------------------------------------------------Now i want to reduce the time of this query.
    If i am removing Order by clause from query than performance of the query is totally perfect but with order by clause its taking a time.
    I have already set SORT_AREA_SIZE but still nothing is improving.
    Welcome and thanks for your suggestions.
    Thanks,
    Edited by: BluShadow on 23-Jun-2011 07:55
    added {noformat}{noformat} tags and formatted explain plan to make it readable.  Please see {message:id=9360002} for details on how to post code and data                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Hi,
    There are a couple of things I do not understand.
    1. Why don't you put {noformat}{noformat} around your code, it makes it so much easier to read, especially your explain plan
    2. You claim that the ORDER BY is problematic compared to no order by. Then why do you choose to post only one plan?
    3. It is hard to understand how your tables relate, and which indexes you have and which you don't.
    - PK_T2_SEQ, does this mean that SEQ alone is primary key of T2?
    - If SEQ is primary key of T2, why do you join on accountno, seq and not just seq?
    - If SEQ is primary key of T2 one of the tables is denormalized.
    4. FK_ACCOUNTNO, is this an index on accountno, alone?
    - Or is this AccountNo, Seq?
    5. Is there no index on T1.EMPNO?
    Above could of course just be a case of my not understanding the names of your indexes.
    So, here are my guesses:
    Above plan is for the ORDER BY query. That means the optimizer, has chosen to full scan PK_T2_SEQ, since data is then read according to the ORDER BY.
    (This could be a bad choice)I
    You could try and order by t1.seq, instead. Result should be the same.
    Regards
    Peter                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • SQL Query to Calculate Total PO Amount

    Hi,
    I'm trying to create a Purchase Order view that includes Total Po Amount. Has anyone done this before and can provide me with the SQL? Or advice on how to write the query to calculate the po_line amounts for each po number?
    I've looked in the POXPOEPO.fmb form for the calculation(code) and looked at several APPS views(ie. PO_Headers_Inq_V) without any success.
    Any help would be appreciated.
    Thanks
    Tony

    Tony, I think this will help you:
    select sum(pl.unit_price * pl.quantity)
    from po_lines_all pl
    , po_headers_all ph
    where ph.segment1 = 1004257 -- po_number
    and ph.po_header_id = pl.po_header_id
    Regards,
    Ricardo Cabral

  • SEQUENCE Select within an SQL Query with an ORDER BY statement

    Does anyone know why you cannot use an ORDER BY statement within an SQL query when also selecting from a SEQUENCE? My query was selecting production data as a result of a filtered search. I want to take the results of the filtered search and create a transaction. I have a sequence for generating transaction numbers where I select NEXTVAL. Since I could possibly obtain multiple, yet distinct, rows based upon my search criteria, I wanted to use an ORDER BY statement to simplify and order the resulting row(s).
    I was able to get the SQL select with SEQUENCE.NEXTVAL to work without the ORDER BY, so I know that my SQL is correct. Thanks in-advance.

    Okay,
    I understand. You want the sequence assigned first and the you want to ORDER BY. You
    can do this using pipelined functions. See here:
    CREATE OR REPLACE TYPE emp_rec_seq AS OBJECT (
       seq     NUMBER,
       ename   VARCHAR2 (20),
       job     VARCHAR2 (20),
       sal     NUMBER
    CREATE OR REPLACE TYPE emp_tab_seq AS TABLE OF emp_rec_seq;
    CREATE OR REPLACE FUNCTION get_emp_with_sequence
       RETURN emp_tab_seq PIPELINED
    IS
       my_record   emp_rec_seq := emp_rec_seq (NULL, NULL, NULL, NULL);
    BEGIN
       FOR c IN (SELECT dummy.NEXTVAL seq, ename, job, sal
                   FROM emp)
       LOOP
          my_record.seq := c.seq;
          my_record.ename := c.ename;
          my_record.job := c.job;
          my_record.sal := c.sal;
          PIPE ROW (my_record);
       END LOOP;
       RETURN;
    END get_emp_with_sequence;after that, you can do a select like this:
    SELECT seq, ename, job, sal
      FROM TABLE (get_emp_with_sequence)
      order by enamewhich will get you this:
           SEQ ENAME                JOB                         SAL
          1053 BLAKE                MANAGER                    2850
          1054 CLARK                MANAGER                    2450
          1057 FORD                 ANALYST                    3000
          1062 JAMES                CLERK                       950
          1055 JONES                MANAGER                    2975
          1052 KING                 MANAGER                   20000
          1060 MARTIN               SALESMAN                   1250
          1063 MILLER               CLERK                      1300
          1064 DKUBICEK             MANAGER                   12000
          1056 SCOTT                ANALYST                    3000
          1058 SMITH                CLERK                       800
          1061 TURNER               SALESMAN                   1500
          1059 WARD                 SALESMAN                   1250Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://htmldb.oracle.com/pls/otn/f?p=31517:1
    -------------------------------------------------------------------

  • JSTL sql:query date field has zero time part

    I have a little JSP where I am using JSTL to do a query against a table "ph_application" that has a date field "rundate". This field has many different dates and times in it.
    Here is the code snippet:
    <sql:setDataSource url="jdbc:oracle:thin:@oraprd02:1521:ipp4" user="site" password="pmc_site"/>
    <sql:query var="application" sql="select * from ph_application"/>
    <c:forEach items="${application.rows}" var="row">
    <tr>
    <td><c:out value="${row.name}" default=" " escapeXml="false"/></td>
    <td><fmt:formatDate value="${row.rundate}" type="both"/></td>
    </tr>
    </c:forEach>
    The resulting date/time output always has a 12:00:00 AM time regardless of what is actually in the table. I have changed the fmt:formatDate to a c:out of the row.rundate.time value and it appears that the time part of the date is actually zero at this point.
    Is there an inconsistancy between the oracle date type and what JSTL is expecting (somewhere)?
    Any help and/or verification is appreciated.
    Richard

    I'm running this from within JDeveloper 10g.

  • Informix / SQL Query to calculate Service Level Met %

    Hi,
    We have a client running UCCX 7.0 and we are upgrading it to 8.5.
    They have a custom .net application that display different stats on IP Phone. I have converted all of them except i am having problem calculating Service Level Met %
    Existing SQL query converts boolean into Float but Informix gives error that boolean can't be converted to float or integer.
    here is part of existing query (SQl Server) to calculate service level met %
    ROUND((SUM(CAST(ssl.metServiceLevel AS FLOAT))/COUNT(CAST(ssl.metServiceLevel AS FLOAT))) * 100,2) AS serviceLevelMet
    I will greatly appreciate if anyone can help converting this query into Informix query format.
    Thank you

    Hi Sonain
    Try this, it won't display a service level until you have received at least one call on the CSQ.
    SELECT csqsum.CSQName,loggedInAgents,talkingAgents,availableAgents,workingAgents,reservedAgents,servicelevel
    FROM  RtCSQsSummary csqSum left outer join
         (SELECT csqname, ROUND(sum(100 * (MetSL)/ (case when (MetSL + NotSL  = 0) then 1 else (MetSL + NotSL) end)) ) as servicelevel
            FROM(
                SELECT
                     trim( csqname) csqname
                    ,sum( case cqd.metServiceLevel when 't' then  1 else 0 end)  MetSL
                    ,sum( case cqd.metServiceLevel when 't' then 0 else 1 end) NotSL
                FROM ContactServiceQueue csq
                    inner join contactqueuedetail cqd  on cqd.targetID = csq.recordID
                    inner join contactroutingdetail crd on crd.sessionID = cqd.sessionID
                    inner join contactcalldetail ccd on crd.sessionID = ccd.sessionID
                WHERE Date(current) - Date(crd.StartDateTime ) = 0
                GROUP BY csqname
            )z
       GROUP BY z.csqname
        )y
    ON y.CSQName = csqsum.CSQName
    Please rate helpfull posts.
    Graham

  • How to write a sql query to calculate weights using CTE

    Hi guys,
    want some help using a CTE to generate data using recursive SQL - input data in table A to be transformed into table B shown below
    Table A
    Instru_id_index     instru_id_name    instru_id_constit  con_name   weight
            56                       INDEX A                     
    23                  A                 25
            56                       INDEX A                     
    24                 B                  25
            56                       INDEX A                     
    25                  C                 25
            56                       INDEX A                     
    57              
    INDEX  B       25
            57                      
    INDEX B                     31                 
    D                 33
            57                      
    INDEX B                     32                 
    E                  33
            57                      
    INDEX B                     33                 
    F                  33
    (Logic should be recursive in order to be able to handle multi-level, not just level 2.)
    Table B
    Instru_id_index     instru_id_name    instru_id_constit  constit_name   weight
            56                       INDEX A                        
    23                A                   25
            56                       INDEX A                        
    24                B                   25
            56                       INDEX A                        
    25                C                   25
            56                       INDEX A                        
    31                D                   8.3
            56                       INDEX A                        
    32                E                    8.3
            56                       INDEX A                        
    33                F                    8.3
            57                       
    INDEX B                       31                
    D                   33
            57                       
    INDEX B                       32                E                   
    33
            57                       
    INDEX B                       33               
    F                     33
    how can I write a simple CTE construct to  display the data in table B -  How can i calculate the values of weights as 8.3 respectively - calculate these without changing the structure of the tables.
    Can I do this in a CTE

    Full join?
    Anyway, thanks for Rsignh to produces a script with CREATE TABLE and INSERT statements. I've extended the data to one more level of recursion.
    create table weight_tab(
     instrument_id_index int,
     instrument_id_name varchar(10),
     instrument_id_constituent int,
     constituent_name varchar(10),
     [weight] decimal(10,2))
     insert into weight_tab values
     (56,'INDEX A',23,'A',25),(56,'INDEX A', 24,'B',25),
    (56,'INDEX A',25,'C',25),(56,'INDEX A', 57,'INDEX  B',25),
    (57,'INDEX B',31,'D',33), (57,'INDEX B', 32,'INDEX E',33),
    (57,'INDEX B',33,'INDEX C',33),
    (33,'INDEX C',42,'Alfa',60),
    (33,'INDEX C',43,'Beta',40),
    (32,'INDEX C',142,'Gamma',90),
    (32,'INDEX C',143,'Delta',10)
    go
    SELECT * FROM weight_tab
    go
    ; WITH rekurs AS (
        SELECT instrument_id_index, instrument_id_name, instrument_id_constituent,
               cast(weight as float) AS weight, cnt = 1
        FROM   weight_tab a
        WHERE  NOT EXISTS (SELECT *
                           FROM   weight_tab b
                           WHERE  b.instrument_id_constituent = a.instrument_id_index)
        UNION ALL
        SELECT r.instrument_id_index, r.instrument_id_name, w.instrument_id_constituent,
               r.weight * w.weight / 100, r.cnt  + 1
        FROM   rekurs r
        JOIN   weight_tab w ON r.instrument_id_constituent = w.instrument_id_index
        WHERE r.cnt < 4
    SELECT instrument_id_index, instrument_id_name, instrument_id_constituent,
           cast(weight AS decimal(10,2))
    FROM   rekurs
    go
    DROP TABLE weight_tab
    Erland Sommarskog, SQL Server MVP, [email protected]

  • SQL Query rewrite, remove ORDER BY clause

    Hello,
    we've just installed a proprietary application which uses an Oracle 11.2.0.2 RAC database. We've seen that one of the auto-generated application's queries
    has poor performance (3-5 minutes for results), the query does a SELECT and at the end it uses an ORDER BY clause. If we remove the ORDER BY clause
    the query returns the results in less than 5 seconds. Unfortunately, we can't re-write the query in the application since we don't have any access to it and
    i was wondering if there is a way to rewrite the specific query from the database.
    We've already seen the SQL Patch but we can change only the hints of the query so we can't remove the ORDER BY clause from it. From what we've seen
    outlines also change only the hints and not the actual sql statement.
    Is there a way to rewrite the specific query from the database ?
    thanks in advance,
    Giannis

    Maybe DBMS_ADVANCED_REWRITE can help but this a SQL question than has very likely nothing to do with RAC.
    See http://www.oracle-base.com/articles/10g/dbms_advanced_rewrite.php.

  • SQL Query...number to time

    Hi,
    I want to know how to a convert number (say, 54678) into hh:mi:ss format.
    Any help.
    Thanks.

    You can test/troubleshoot it. This may or may not be perfect, you need to reverse engineer it and find (any) mistakes/logic errors. Hint: there is one.
    set serveroutput on
    create or replace procedure get_time (sod in number) as
      v_diff number;
      v_current number;
      v_date date;
    begin
      v_current := to_number(to_char(sysdate,'SSSSS'));
    --  dbms_output.put_line('v_current is '||v_current);
      v_diff := v_current - sod;
    --  dbms_output.put_line('v_diff is '||v_diff);
      --evaluate the difference
      if v_diff < 0 then
        --means number of seconds is in the future
        v_date := sysdate - v_diff/86400;
      elsif v_diff > 0 then
        --means sod is in the past
        v_date := sysdate + v_diff/86400;
      else
        --means you got lucky
        v_date := sysdate;
      end if;
      dbms_output.put_line('At the tone, the time is '||to_char(v_date,'HH:MI:SS PM'));
    end;
    exec get_time(54678);
    At the tone, the time is 03:11:18 PM
    PL/SQL procedure successfully completed.Message was edited by:
    stevencallan
    Message was edited by:
    stevencallan

  • Maintenance order completion time

    dear all .
    can we get actual working time for completing the maintenance order.
    thanks

    Hi
    Check in IW47, its a report.
    To get the actual confirmation
    BAPI_ALM_CONF_GETDETAIL
    BAPI_ALM_CONF_GETLIST
    Get an help with the abaper and check this.
    - Pithan

  • Sql query when fired for first time

    Here is my query. I installed database and software using DBCA. Now i got connected to sql. Now my doubt is when I fired SELECT * FROM EMP from scott user, for the first time, what are the different steps followed to fectch the data. I mean how the user gets connected to the database and which background process works at what stages. Please give detailed explanation. Thanks.

    When connecting to the database the client makes a request to the listener, and the listener checks the availability of the requested database service and responds to the client with an ACCEPT message, which indicates connection dispatching.
    After that, the listener sends a RESEND message back to the client and uses this time to check the database service. The client recieves the RESEND message and sends the same request again to the Listener.
    After recieving the ACCEPT message the connection is established, and this connection is different depending if you are using a Dedicated Server or Shared Server configuration.
    When you issue the query:
    SELECT * FROM emp;Oracle checks in the Shared Pool, in the Data Dictionary cache if the object exists and if you have sufficient privileges to access it (user Scott in this case). It then checks the Library cache if this statement has been executed before. If it did, another parse will not be necessary. Then the SQL statement is parsed (if necessary), interpreted and executed.
    The DBRW (Database Writer) background process then checks in the Buffer Cache if the blocks which contain the information from the EMP table are already there. If they are, a physical read is not necessary and it fetches the rows from the Buffer Cache.
    If they are not, DBWR reads the data files, retrieves the data from them, store the related blocks in the Buffer Cache (so in the next executions of this query a physical read will not be needed) and then the data is shown to the user.
    There are other details envolved, but in a general view that is what happens.

  • SQl Query to Calculate No of Days from LastDate and PreviousDate

    Hi All,
    Below is a sample table which holds the rent updates done for properties at any point of time.
    I like the query to show the out put as
    Prop_Code, PreviousRent, PreviousRentUpdateDate, LastRent, LastRentUpdateDate  NoofDays
    1008             206.38           2014-06-16                    
        209.04     2014-12-22               189
    DECLARE @table TABLE
     ( Prop_Code INT
     ,Current_Rent INT
     ,Revised_Rent INT
     ,Rent_Review_Date varchar(10)
     ,Rent_Review_Time DATEtime)
    INSERT INTO @table (PROP_CODE,Current_Rent,Revised_Rent,Rent_Review_Date,Rent_Review_Time) VALUES
    (2977,372,339.15,'2013-07-08','7:44')
    ,(2977,372,339.15,'2013-07-03','11:01')
    ,(2977,372,372,'2014-06-30','9:07')
    ,(2977,372,372,'2014-07-07','11:06')
    ,(2981,372,372,'2014-07-07','11:06')
    ,(2981,372,340.15,'2013-07-08','7:23')
    ,(2981,372,314.15,'2013-07-08','7:44')
    ,(2981,372,340.15,'2013-07-29','7:16')
    ,(3089,205.63,400,'2014-10-27','8:38')
    ,(3089,205.63,205.63,'2014-02-03','8:29')
    ,(3089,205.63,127.64,'2014-01-20','0:52')
    ,(3089,205.63,123.02,'2013-08-12','8:28')
    ,(3089,205.63,205.63,'2014-12-15','8:46')
    ,(3109,252.62,198,'2014-01-20','0:52')
    ,(3109,252.62,252.62,'2014-04-07','8:30')
    ,(3109,252.62,198,'2013-08-12','8:28')
    ,(3117,284.96,336,'2014-04-21','1:03')
    ,(3125,267.53,267.53,'2014-02-03','8:29')
    ,1008,       181.32, '2013-03-19, '04:41')
    ,(1008 ,      186.15, '2013-03-19, '04:41')
    ,(1008 ,      187.62, '2013-03-19, '04:41')
    ,(1008,       191.07, '2013-03-19, '04:41')
    ,(1008,      202.33, '2013-08-12', '08:28')
    ,(1008,       202.53, '2013-11-25', '08:33')
    ,(1008,       206.38, '2014-06-16', '09:38')
    ,(1008,       209.04, '2014-12-22', '07:55')
    Select * from @table
    Regards,
    Jag

    INSERT statement had error and incorrect data. I changed it
    Rent column had INT data type and I changed it to Money.
    DECLARE @table TABLE
    ( Prop_Code INT
    ,Current_Rent Money
    ,Revised_Rent Money
    ,Rent_Review_Date varchar(10)
    ,Rent_Review_Time DATEtime)
    INSERT INTO @table (PROP_CODE,Current_Rent,Revised_Rent,Rent_Review_Date,Rent_Review_Time) VALUES
    (2977,372,339.15,'2013-07-08','7:44')
    ,(2977,372,339.15,'2013-07-03','11:01')
    ,(2977,372,372,'2014-06-30','9:07')
    ,(2977,372,372,'2014-07-07','11:06')
    ,(2981,372,372,'2014-07-07','11:06')
    ,(2981,372,340.15,'2013-07-08','7:23')
    ,(2981,372,314.15,'2013-07-08','7:44')
    ,(2981,372,340.15,'2013-07-29','7:16')
    ,(3089,205.63,400,'2014-10-27','8:38')
    ,(3089,205.63,205.63,'2014-02-03','8:29')
    ,(3089,205.63,127.64,'2014-01-20','0:52')
    ,(3089,205.63,123.02,'2013-08-12','8:28')
    ,(3089,205.63,205.63,'2014-12-15','8:46')
    ,(3109,252.62,198,'2014-01-20','0:52')
    ,(3109,252.62,252.62,'2014-04-07','8:30')
    ,(3109,252.62,198,'2013-08-12','8:28')
    ,(3117,284.96,336,'2014-04-21','1:03')
    ,(3125,267.53,267.53,'2014-02-03','8:29')
    ,(1008, NULL ,181.32, '2013-03-19', '04:41')
    ,(1008 , NULL , 186.15, '2013-03-19', '04:41')
    ,(1008 ,NULL , 187.62, '2013-03-19', '04:41')
    ,(1008, NULL , 191.07, '2013-03-19', '04:41')
    ,(1008, NULL , 202.33, '2013-08-12', '08:28')
    ,(1008, NULL , 202.53, '2013-11-25', '08:33')
    ,(1008, NULL , 206.38, '2014-06-16', '09:38')
    ,(1008, NULL , 209.04, '2014-12-22', '07:55')
    WITH TempCTE
    AS (
    SELECT *
    ,ROW_NUMBER() OVER (
    PARTITION BY Prop_Code ORDER BY Rent_Review_Date DESC
    ) RowNum
    FROM @table
    SELECT a.Prop_Code
    ,a.Revised_Rent
    ,a.Rent_Review_Date
    ,b.Revised_Rent
    ,b.Rent_Review_Date
    ,DATEDIFF(Day, a.Rent_Review_Date, b.Rent_Review_Date)
    FROM TempCTE a
    INNER JOIN TempCTE b ON a.Prop_Code = b.Prop_Code
    AND a.RowNum = b.RowNum + 1
    WHERE b.RowNum = 1
    -Vaibhav Chaudhari

  • How to order SQL query results in order given in IN Clause

    Hi,
    I Need to construct a query, which takes a string as input and results for those should be sorted in the order in which request was made.
    Say, we have a couple of students, and the grades in different subjects to be the result of the query.
    If John and Jane are the two students,
    and if input is John,Jane
    my output should be listing John, his subjects and grades
    and then Jane, her subjects and grades.
    I read somewhere in other posts, that i could use a query combined with regular expression to split a string into a temp table/array and use this as my input for my select query. Then use the rownum or level from this temp table to sort the data in order sent in.
    But am not able to put together a query which would work for me.
    Anyone with any pointers on this would be highly appreciated.
    Thanks

    Hi,
    [This thread|http://forums.oracle.com/forums/thread.jspa?threadID=702891&tstart=0] is about splitting up delimited lists. You'll want to keep the n-th value from the user-supplied list, as well as n itself, in a result set, so you can use it in both your WHERE- and your ORDER BY clause.
    If you're using SQL*Plus, you can also keep the whole list in a substriution variable, and use INSTR to see where individual values appeard in that list. Personally, I'd trust the first method (split and store) more.

  • Sql query to calculate total credit having more than one tables

    i have these 9 tables and want to calculate totalcredit from these tables alse want to
    See more: SQL-server-2008R2
    i have these 9 tables and want to calculate totalcredit from these tables alse want to calculate totaldebit of all account no in which each accountno will show its own total credit and total debit 
    parties
    purchase 
    purchase body
    purchase return
    purchase return body
    sale 
    sale body
    sale return
    sale return body

    If you want to suggest you accurate solution, please post CREATE TABLE+ INSERT INTO + sample data + DESIRED RESULT
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

Maybe you are looking for

  • FIELDS MISSING

    Hi, When i replicated CO-PA data into BI. It created two DS's: 0COPA_RCTY AND 1_CO_PA_XXXXXXX I created an Infosource and transfer rules for 1_CO_PA_XXXXXXX but there are a few fields missing that i do see in the operating concern such as: ARTNR=0MAT

  • Update Record Field if Value Not Equal

    Hello All, I am using Toad for Oracle 10. I have a MERGE INTO Process that updates tbl_requisition based on FK - fk_allotment_id that equals parent table tbl_allotment PK - pk_allotment_id. Both tables have create, update and deletes triggers. The pr

  • Disappearing Applications - Feels Like a Virus...

    My computer's been behaving really strangely today. First, I tried to open Quicksilver from the Dock, and Quicksilver's missing. (I've deleted nothing, and used the program yesterday.) This morning I was able to use Firefox. I turned off my computer

  • NI 9402 frequency measurement

    Hi Forum I have: Dasylab 11, NI cDaq with a 9402 high speed digital input/output module, Newest version of Daqmx driver I am using the 9402 module to measure the frequency of a squre pulse signal. 1) But when I run the setup in Dasylab, I get the sam

  • BGP Update Messages

    Can a bgp UPDATE message carry more than a single prefix ? I have read a lot of text about this ( Halabi, Doyle, RFC 1771 ) but I think the wording that this literature is never clear to me about what they are exactly saying. below is a quote from RF