Please explain the query?

hello all,
please explain below query used in solution below, thanks in advance!
ELECT MAX(P1.ET) AS ST, P2.ST AS ET
FROM XYZ AS P1
INNER JOIN XYZ AS P2 ON (P1.ST < P2.ST)
GROUP BY P2.ST
HAVING MAX(P1.ET) < P2.ST
IF OBJECT_ID('XYZ') IS NOT NULL
DROP TABLE XYZ
GO
CREATE TABLE XYZ
id int identity(1,1),
ST smalldatetime NOT NULL,
ET smalldatetime NOT NULL
GO
INSERT INTO XYZ (ST, ET)
VALUES ('2010-01-01 9:00AM', '2010-01-01 10:00AM')
INSERT INTO XYZ (ST, ET)
VALUES ('2010-01-01 9:00AM', '2010-01-01 12:00PM')
INSERT INTO XYZ (ST, ET)
VALUES ('2010-01-01 1:00PM', '2010-01-01 2:00PM')
INSERT INTO XYZ (ST, ET)
VALUES ('2010-01-01 3:00PM', '2010-01-01 5:00PM')
INSERT INTO XYZ (ST, ET)
VALUES ('2010-01-01 11:00AM', '2010-01-01 12:00PM')
GO
WITH Gaps(Gap) AS
SELECT COALESCE(SUM(DATEDIFF(MINUTE,ST,ET)), 0)
FROM (
SELECT MAX(P1.ET) AS ST, P2.ST AS ET
FROM XYZ AS P1
INNER JOIN XYZ AS P2 ON (P1.ST < P2.ST)
GROUP BY P2.ST
HAVING MAX(P1.ET) < P2.ST
) gaps
SELECT (
COALESCE(DATEDIFF(MINUTE, MIN(ST), MAX(ET)), 0)
- (SELECT Gap FROM Gaps)
) / 60.0 TotalHrs
FROM XYZ

SELECT MAX(P1.ET) AS ST, P2.ST AS ET
FROM XYZ AS P1
INNER JOIN XYZ AS P2 ON (P1.ST < P2.ST)
GROUP BY P2.ST
HAVING MAX(P1.ET) < P2.ST
Finds all of the gaps (that is time that is not in any interval in your original data.  To see how it works, let's look at an example.  I'm going to use data that is a little different than your original data because your data has no gaps. 
The query still works if you have no gaps, but it is easier to see what it is doing if the data has some gaps.  Also, I'm going to explicitly set the id column instead of making it an identity.  This will make it a little easier to identify each
row in the following explanation. So the data I'm going to work with is
CREATE TABLE XYZ
id int,
ST smalldatetime NOT NULL,
ET smalldatetime NOT NULL
GO
INSERT INTO XYZ (id, ST, ET)
VALUES (1, '2010-01-01 9:00AM', '2010-01-01 10:00AM')
INSERT INTO XYZ (id, ST, ET)
VALUES (2, '2010-01-01 9:00AM', '2010-01-01 12:00PM')
INSERT INTO XYZ (id, ST, ET)
VALUES (3, '2010-01-02 1:00PM', '2010-01-02 2:00PM')
INSERT INTO XYZ (id, ST, ET)
VALUES (4, '2010-01-03 3:00PM', '2010-01-03 5:00PM')
INSERT INTO XYZ (id, ST, ET)
VALUES (5, '2010-01-03 7:00PM', '2010-01-03 9:00PM')
Notice that the gaps here are from row 2 to row 3 (12PM on the 1st to 1PM on the 2nd) and row 3 to row 4 (2PM on the 2nd to 3PM on the 3rd) and row 4 to row 5 (5PM on the 3rd to 7PM on the 3rd).  So that's what the above subquery should be finding for
us.
To see what a query you don't understand is doing, simplify it to the smallest part you can and see what it returns and then build it up to the final query.  So the simplest thing we can do is just the from clause.  That gives us
SELECT *
FROM XYZ AS P1
INNER JOIN XYZ AS P2 ON (P1.ST < P2.ST)
/* That gives us the result
1 2010-01-01 09:00:00 2010-01-01 10:00:00 3 2010-01-02 13:00:00 2010-01-02 14:00:00
2 2010-01-01 09:00:00 2010-01-01 12:00:00 3 2010-01-02 13:00:00 2010-01-02 14:00:00
1 2010-01-01 09:00:00 2010-01-01 10:00:00 4 2010-01-03 15:00:00 2010-01-03 17:00:00
2 2010-01-01 09:00:00 2010-01-01 12:00:00 4 2010-01-03 15:00:00 2010-01-03 17:00:00
3 2010-01-02 13:00:00 2010-01-02 14:00:00 4 2010-01-03 15:00:00 2010-01-03 17:00:00
1 2010-01-01 09:00:00 2010-01-01 10:00:00 5 2010-01-03 19:00:00 2010-01-03 21:00:00
2 2010-01-01 09:00:00 2010-01-01 12:00:00 5 2010-01-03 19:00:00 2010-01-03 21:00:00
3 2010-01-02 13:00:00 2010-01-02 14:00:00 5 2010-01-03 19:00:00 2010-01-03 21:00:00
4 2010-01-03 15:00:00 2010-01-03 17:00:00 5 2010-01-03 19:00:00 2010-01-03 21:00:00
Now we want to Group by P2.ST and get the MAX(P1.ET) and P2.ST, so that gives us
SELECT MAX(P1.ET) AS ST, P2.ST AS ET
FROM XYZ AS P1
INNER JOIN XYZ AS P2 ON (P1.ST < P2.ST)
GROUP BY P2.ST
/* Result is
2010-01-01 12:00:00 2010-01-02 13:00:00
2010-01-02 14:00:00 2010-01-03 15:00:00
2010-01-03 17:00:00 2010-01-03 19:00:00
Now with this sample data there are no rows in the output with MAX(P1.ET) > P2.ST.  But if there was one, you would not want that row because it is not a real gap (obviously, a gap can't start today and end yesterday).  (If you want to see how
you could get a case like that, add a row 6 to the sample data with a ST of 2010-01-01 7:00PM and an ET of 2010-01-03 9:00PM.)
So we add a HAVING MAX(P1.ET) < P2.ST to remove those cases.
That leaves us with all of the gaps.  So then with
SELECT COALESCE(SUM(DATEDIFF(MINUTE,ST,ET)), 0)
FROM (
SELECT MAX(P1.ET) AS ST, P2.ST AS ET
FROM XYZ AS P1
INNER JOIN XYZ AS P2 ON (P1.ST < P2.ST)
GROUP BY P2.ST
HAVING MAX(P1.ET) < P2.ST
) gaps
we get the total amount of time in all gaps.  Then the final result is just the time from the earliest ST to the latest ET minus the total time from the gap.
Tom

Similar Messages

  • Can u explain the query?

    select file_name,
    ceil( (nvl(hwm,1)*8192)/1024/1024 ) possible,
    ceil( blocks*8192/1024/1024) current,
    ceil( blocks*8192/1024/1024) -
    ceil( (nvl(hwm,1)*8192)/1024/1024 ) saving
    from dba_data_files a,
    ( select file_id, max(block_id+blocks-1) hwm
    from dba_extents
    group by file_id ) b
    where a.file_id = b.file_id(+) and a.tablespace_name = '&tsname'
    can u please explain the query and wat does ceil mean ??

    can u please explain the query and wat does ceil mean ??http://www.psoug.org/reference/number_func.html
    SQL> SELECT CEIL(12345.67) FROM dual;
    CEIL(12345.67)
             12346
    SQL> SELECT CEIL(12345.99) FROM dual;
    CEIL(12345.99)
             12346
    SQL> SELECT CEIL(12345.00) FROM dual;
    CEIL(12345.00)
             12345
    SQL>

  • Please explain,  the job of the  "ASSIGN COMPONENT ".

    Please read this popular example appended below. I am newbie to ABAP.
    At the end of the execution the code is printing 33. Don't get it.
    Please explain,  the job of the  "ASSIGN COMPONENT ". How or why it is printing value 33.  What is the meaning of the statement, "ASSIGN COMPONENT <F2> OF STRUCTURE <F1> TO <F3>." ?
    DATA: BEGIN OF LINE,
    COL1 TYPE I VALUE '11',
    COL2 TYPE I VALUE '22',
    COL3 TYPE I VALUE '33',
    END OF LINE.
    DATA COMP(5) VALUE 'COL3'.
    FIELD-SYMBOLS: <F1>, <F2>, <F3>.
    ASSIGN LINE TO <F1>.
    ASSIGN COMP TO <F2>.
    DO 3 TIMES.
    ASSIGN COMPONENT SY-INDEX OF STRUCTURE <F1> TO <F3>.
    WRITE <F3>.
    ENDDO.
    ASSIGN COMPONENT <F2> OF STRUCTURE <F1> TO <F3>.
    WRITE / <F3>.
    11 22 33
    33

    DATA: BEGIN OF LINE,
    COL1 TYPE I VALUE '11',
    COL2 TYPE I VALUE '22',
    COL3 TYPE I VALUE '33',
    END OF LINE.
    DATA COMP(5) VALUE 'COL3'.
    FIELD-SYMBOLS: <F1>, <F2>, <F3>.
    ASSIGN LINE TO <F1>.
    ASSIGN COMP TO <F2>.      "here you are assigning the column name which is COL3 to <f2>.
    DO 3 TIMES.
    ASSIGN COMPONENT SY-INDEX OF STRUCTURE <F1> TO <F3>.
    WRITE <F3>.
    ENDDO.
    ASSIGN COMPONENT <F2> OF STRUCTURE <F1> TO <F3>.
    ASSIGN 'COL3' of structure <f1> to <f3>. "it is equal to above statement.
    WRITE / <F3>.
    11 22 33
    33
    ASSIGN COMPONENT <F2> OF STRUCTURE <F1> TO <F3>. means
    assigining  COL3  value of the structure <f1> to <f3>, so value is 33 , it will be assigned to <f3> .it prints 33.

  • Please explain the use of all the below movt types

    Hi friends,
    Can you Please explain the use of all the below movt types and how it is triggered.
    901     GR Area for Production
    902     GR Area External Rcpts
    904     Returns
    910     GI Area General
    911     GI Area for Cost Center
    912     GI Area Customer Order
    913     GI Area - Fixed Assets
    914     GI Area Production Orders
    915     Fixed Bin Picking Area
    916     Shipping Area Deliveries
    917     Quality Assurance
    920     Stock Transfers (Plant)
    921     Stock Transfers (StLoc)
    922     Posting Change Area
    980     R/3 --> R/2 cumulative
    998     Init.entry of stock bal.
    999     Differences
    Regards,
    Balu R.V

    Hi,
    The below mentioned objects are interim storage types, not movement types.
    Interim storage types are used as a sort of bridge between IM and WM.
    MZ

  • Please explain the magic! (Question)

    The ActionScript snippet below is from the BlaseDS chat sample app. Can someone please explain the magic that declares the chatMessage property of AsyncMessage.body (IMessage.body?) object? It's not in the docs anywhere so I'm guessing it is not built into AsyncMessage. And it's not defined in any of the sample app source files.
    Coming from a strongly-typed development world, seeing a property that apparently has no declaration and is not explicitly instantiated does not pass the sniff-test.
    Thanks.
    <mx:Script>
      <![CDATA[
       import mx.messaging.messages.AsyncMessage;
       import mx.messaging.messages.IMessage;
       private function send():void
        var message:IMessage = new AsyncMessage();
        message.body.chatMessage = msg.text;
        producer.send(message);
        msg.text = "";
       private function messageHandler(message:IMessage):void
        log.text += message.body.chatMessage + "\n";
      ]]>

    Hold your nose, because that is the dynamic "feature" of Actionscript.  Pretty much every class derives from Object (http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Object.html) which is a dictionary of key-value property pairs.  The {"chatMessage", msg.text as Object} pair is created upon assignment.
    I am fairly new to Flex/AS, and while not having to declare types is convenient for quick and dirty coding, I try to avoid it in production code...I have been bitten by refactoring a class and not catching all the places where it was referenced dynamically.  I'm sure there are comprehensive pro and con arguments out there.

  • 2 GB Limit – Please explain the concept

    I have more than 35000 photos already uploaded into Revel.
    In order to continue to remain a Free member, shall I have to delete all my photos and keep only within 2 GB limit?
    Please explain the new concept... Thanks!

    You may continue to use revel free of charge with the new model change, however, if you have stored more than 2 GB of files, then you will be unable to upload any additional photos/videos until you delete some files to take you below the limit or subscribe to get unlimited uploads.
    Pattie

  • TS1503 In the iPhone, please explain the requirements in settings for Apple id, iPhone and iCloud

    In the iPhone, please explain the requirements in settings for Apple id, iPhone and iCloud

    You can use 1 unified Apple ID for iTunes so you don't have to repurchase apps.   That part is fine.
    For iCLoud/iMessage/Facetime you should each have a unique ID so the 2 phones will be separate and you won't accidentally erase each other's content and overwrite settings, nor will you get the others messaages by mistake.

  • The query processor ran out of stack space during query optimization. Please simplify the query

    Can you suggest me that what should i do in this case.
    Actually i am having one table that is a MasterTable.I am referring this table in more than 300 tables that means i am having foreign key of this primary key in 300+ tables.
    due to this i am getting following error during deleting any row,
    doesn't matter that data is existing in reference table or not.
    Error that i am getting is 
    "The query processor ran out of stack space during query optimization. Please simplify the query"
    Can you suggest me that what should i do to avoid this error,because i am unable to delete this entry.
    Apart from it,i am getting performance problem too,so is it due to such huge FK on it.
    Please suggest me on following points
    1. Is it worst way to handle it,if yes then please suggest me solution for it.
    2. If it is a correct way then what should i do if getting error during deleting any record.
    3. Is it right to create Foreign key on each table where i am saving data of this master. if no then how to manage integrity.
    4. What people do in huge database when they wants to create foreign key for any primary key.
    5. Can you suggest me that how DBA's are handling this in big database,where they are having huge no. of tables.

    The most common reason of getting such error is having more than 253 foreign key constraints on a table. 
    The max limit is documented here:
    http://msdn.microsoft.com/en-us/library/ms143432(SQL.90).aspx 
    Although a table can contain an unlimited number of FOREIGN KEY constraints, the recommended maximum is 253. Depending on the hardware configuration hosting SQL Server, specifying additional foreign key constraints may be expensive for the query
    optimizer to process. If you are on 32 bit, then you might want to move to 64 bit to get little bigger stack space but eventually having 300 FK is not something which would work in long run.
    Balmukund Lakhani | Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    This posting is provided "AS IS" with no warranties, and confers no rights.
    My Blog |
    Team Blog | @Twitter
    Author: SQL Server 2012 AlwaysOn -
    Paperback, Kindle

  • Please explain the following terms in SRM

    Hi Forum,
    I am new to SRM and trying to understand some general terms and concepts in SRM.
    Please explain the meaning of below jargons if possible with an example and what is their use in SRM bussiness scenarios...
    1. Company Code
    2. Account Assignment Category - CC, OR etc
    3. Cost Center
    4. Document Types
    5. Transaction Types
    6. Movement Types
    7. Storage Location
    8. Plants
    9. Central Person
    10. Business Partner
    I am trying to understand what is the relevance of above things in SRM/ECC ?
    Thanks,
    Vivek

    Vivek
    It would be great if you go through http://help.sap.com/saphelp_srm30/helpdata/en/8d/f6a93e08503614e10000000a114084/frameset.htm
    This will help you clear most of your queries.
    Regards,
    Nikhil

  • Could someone please explain the difference between Projects Intelligence and Projects Analytics?

    Could someone please explain the difference between Projects Intelligence and Projects Analytics?
    Thanks,
    Adrien

    Older iPads got 3G service and were called Wi-Fi + 3G. Newer iPads can connect to faster cellular networks and those are given different names by the major carrier so to simplify things Apple calls the newer models Wi-Fi + Cellular.
    iPads with 3G or Cellular are NOT used like a mobile phone. They do not make phone calls or send SMS or MMS text messages, They do connect to the data network and can connect to the web.

  • Can any please explain the integration business process between PS and CS

    Dear Guru's
    Can any please explain the integration business process between Project systems (PS) and customer service (CS).
    Business Process: We do machinery Erection or commissioning, later we do provide service warranty for one year.
    How we map this Business scenario in sap.
    Regards,
    Bhanu

    basic steps for such a process would be
    1) Use PS functionality for your machinery erection or commisioning work. Once the physical work is completed then close porject
    2) Use CS functionality for warranty and service - set up the work as a functional location on customer site (PM/CS functionality)
    3) Use service order to manage any service calls on the object which could require billing via SD module - bill value may be zero if under warranty

  • A consent for a new eula, please explain the ramification of these new terms

    4. Your Compliance With This Agreement.
    You acknowledge that your compliance with the terms of this Agreement may require you to provide certain notices to, obtain certain rights from, and impose certain obligations on your Clients and/or users of the websites hosted by the Services. To that end, you agree that each website for which Adobe provides Services on your behalf (including, if you are a Partner, your Clients’ websites) will contain a clear and conspicuous link to a terms of use and a privacy policy that comply with all applicable laws, rules, and regulations.
    5. Partner Obligations.
    (c) You are responsible for your Clients’ compliance with applicable laws in connection with their use of the Services.
    (g) You have or will obtain all rights necessary for you to grant Adobe the licenses granted in Section 16 (“Content”), below.
    16. Content.
    You (if you are a Site Owner) or your End Users (if you are a Partner), and/or each such party’s respective licensors, retain ownership of any information, content and/or materials that they submit in the course of using the Services (“Content”); however, Adobe needs certain rights to Content in order to provide the Services. Accordingly, you hereby grant to Adobe and its service providers and designees a worldwide, non-exclusive, transferable, sublicensable (through multiple tiers), royalty-free, perpetual, irrevocable right and license, without compensation to you: to use, reproduce, distribute, adapt (including without limitation edit, modify, translate, and reformat), create derivative works of, transmit, publicly display and publicly perform such Content, in any media now known or hereafter developed.
    please explain the ramification of these new terms
    Thank you,
    Lana

    Hi guys,
    Correct as Liam noted there are various topics on these concerns. 
    However if still having issues/concerns I would suggest posting in the original thread below after reviewing Magda's response.
    - http://forums.adobe.com/message/4353638
    Kind regards,
    -Sidney

  • Please explain the logic.

    select * from
    from cust b
         LEFT OUTER JOIN
         cust a
         ON
         (a.sales_date+1=b.sales_date)
         WHERE TRIM(TO_CHAR(b.sales_date,'DAY')) IN ('SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY')
         AND b.sales_Date BETWEEN TO_DATE(V_START_DATE,'DD-MON-YY') AND to_date(V_END_DATE,'DD-MON-YY')
         AND a.sales_Date BETWEEN TO_DATE(V_START_DATE,'DD-MON-YY')-1 AND to_date(V_END_DATE,'DD-MON-YY')
    Could someone explain the logic behind the query above?
    Thanks,
    Bhagat

    Bugs wrote:
    select * from
    from cust b
         LEFT OUTER JOIN
         cust a
         ON
         (a.sales_date+1=b.sales_date)
         WHERE TRIM(TO_CHAR(b.sales_date,'DAY')) IN ('SUNDAY','MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY')
         AND b.sales_Date BETWEEN TO_DATE(V_START_DATE,'DD-MON-YY') AND to_date(V_END_DATE,'DD-MON-YY')
         AND a.sales_Date BETWEEN TO_DATE(V_START_DATE,'DD-MON-YY')-1 AND to_date(V_END_DATE,'DD-MON-YY')
    Could someone explain the logic behind the query above?
    Thanks,
    BhagatDoes this query even run? It has syntax error. You have lot of post under your name. So by now you must be knowing the usage of {noformat}{noformat} tag. So please use them to format the code.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Please give the query to find out primary key in table in Sql plus

    Dear friends,
    Please give me the query to find out the primary key in Sql plus.

    hi
    SQL> DESC user_constraints
    Name                                                                                                  
    OWNER                                                                                                 
    CONSTRAINT_NAME                                                                                       
    CONSTRAINT_TYPE                                                                                       
    TABLE_NAME                                                                                            
    SEARCH_CONDITION                                                                                      
    R_OWNER                                                                                               
    R_CONSTRAINT_NAME                                                                                     
    DELETE_RULE                                                                                           
    STATUS                                                                                                
    DEFERRABLE                                                                                            
    DEFERRED                                                                                              
    VALIDATED                                                                                             
    GENERATED                                                                                             
    BAD                                                                                                   
    RELY                                                                                                  
    LAST_CHANGE                                                                                           
    INDEX_OWNER                                                                                           
    INDEX_NAME                                                                                            
    INVALID                                                                                               
    VIEW_RELATED                                                                                          
    SQL> SELECT constraint_name,table_name,r_constraint_name,status
      2  FROM user_constraints WHERE constraint_type='P';
    CONSTRAINT_NAME                TABLE_NAME                     R_CONSTRAINT_NAME              STATUS
    SYS_C003141                    CUSTOMERS                                                     ENABLED
    PK_DEPT                        DEPT                                                          ENABLED
    SYS_C003139                    SALESREPS                                                     ENABLEDKhurram

  • Please explain the following displayed properties

    Hi,
    I tried to change the format of displayname under search result rendering setting. I found the following string for displaying display name:
    <b>rnd:displayname(contentLink/[1;2-3]/alignTop/space-right=30</b>
    please explain how this setting works? for example how that contentLink/[1;2-3] works? is there other setting I can use? like contentLink/1?
    Thanks!
    T.J.

    Hi T.J.
    First read this:
    http://help.sap.com/saphelp_nw04/helpdata/en/79/a1d23e6b2c3d67e10000000a114084/frameset.htm
    There are multiple property renderers available for some properties. Simply using the property name
    instead of the property name with rnd: namespace will typically display the property value in a
    more primitive way than the formatted rnd: version. For instance, the rnd: version for description
    will truncate the text whereas the raw version will not.
    The bracket syntax is used to postion the properties in grid renders like the search results layout sets.
    Regards,
    Darin

Maybe you are looking for