Please explain the sql

Hi All,
If anybody explain me briefly about the following Update statements
Thanks for you rhelp
1)UPDATE MRCH.MRC_TEMP_PAY A
     SET OFFSET = (SELECT MIN(NEW_PAY) FROM MRCH.MRC_TEMP_PAY B
WHERE A.PROJECT_ID = B.PROJECT_ID
AND A.MUNI = B.MUNI
AND B.NEW_PAY < -1
AND PAY_IND = 'N')
     WHERE A.NEW_PAY > 100
     AND A.PAY_IND = 'Y'
     AND A.PINSUB = (SELECT MIN(PINSUB) FROM MRCH.MRC_TEMP_PAY B
     WHERE A.PROJECT_ID = B.PROJECT_ID
     AND A.MUNI = B.MUNI
     AND B.NEW_PAY = (SELECT MAX(NEW_PAY) FROM MRCH.MRC_TEMP_PAY C
     WHERE C.PROJECT_ID = B.PROJECT_ID
     AND C.MUNI = B.MUNI
     AND C.NEW_PAY > 0
     AND C.PAY_IND = 'Y'));
-- NOW GET OFFSET PHASE
2)UPDATE MRCH.MRC_TEMP_PAY A
SET OFFSET_PH = (SELECT PHASE FROM MRCH.MRC_TEMP_PAY B
WHERE A.PROJECT_ID = B.PROJECT_ID
AND A.MUNI = B.MUNI
AND A.OFFSET = B.NEW_PAY)
WHERE A.PAY_IND = 'Y'
AND OFFSET IS NOT NULL;
-- CALCULATE NEW PAYMENT ADDING OFFSET
3) UPDATE MRCH.MRC_TEMP_PAY
     SET NEW_PAY = NEW_PAY + OFFSET
     WHERE OFFSET IS NOT NULL
     AND PAY_IND = 'Y';
     COMMIT;
     -- CHECK ANOTHER PHASE FOR OFFSET
4)UPDATE MRCH.MRC_TEMP_PAY A
     SET OFFSET2 = (SELECT MIN(NEW_PAY) FROM MRCH.MRC_TEMP_PAY B
WHERE A.PROJECT_ID = B.PROJECT_ID
AND A.MUNI = B.MUNI
AND B.NEW_PAY < -1
AND B.NEW_PAY != A.OFFSET
AND B.PAY_IND = 'N')
     WHERE A.NEW_PAY > 100
     AND A.PAY_IND = 'Y'
     AND A.PINSUB = (SELECT MIN(PINSUB) FROM MRCH.MRC_TEMP_PAY B
     WHERE A.PROJECT_ID = B.PROJECT_ID
     AND A.MUNI = B.MUNI
     AND B.NEW_PAY = (SELECT MAX(NEW_PAY) FROM MRCH.MRC_TEMP_PAY C
     WHERE C.PROJECT_ID = B.PROJECT_ID
     AND C.MUNI = B.MUNI
     AND C.NEW_PAY > 0
     AND C.PAY_IND = 'Y'))
     AND A.OFFSET IS NOT NULL;
     5)UPDATE MRCH.MRC_TEMP_PAY A
     SET OFFSET_PH2 = (SELECT PHASE FROM MRCH.MRC_TEMP_PAY B
WHERE A.PROJECT_ID = B.PROJECT_ID
AND A.MUNI = B.MUNI
AND A.OFFSET2 = B.NEW_PAY)
     WHERE A.NEW_PAY > 100
     AND A.PAY_IND = 'Y'
     AND A.OFFSET2 IS NOT NULL;
6)     UPDATE MRCH.MRC_TEMP_PAY
     SET NEW_PAY = NEW_PAY + OFFSET2
     WHERE OFFSET2 IS NOT NULL
     AND PAY_IND = 'Y';

Second query:
If the pay_ind column is yes and offset is not null then the offset_ph is set to the value returned by the inner query. The inner query returns the values of phase.
This is an example of correlated query. So the inner query is executed once for every row in the outer query.
For more information on correlated queries refer to:
http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96540/statements_103a.htm#2066913
Third query:
This query adds the offset value to the pay if pay_id is yes and the offset is not null.
fifth query:
Same as third
The first and the fourth queries can be explained better if the names of the columns and the scenario are known.
Both are using correlated subqueries which are very costly.
Regards,
Anupama

Similar Messages

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

  • 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 Fault policy for my process

    Hi All
    I am new to SOA ,In my process i need to do fault handling,iam providing my process details below anybody please help me regarding this..
    A.Use SQL view to get details
    B. Check originator’s existence
    a) If it not present, add error code 30 to error list and return result.
    b) If it throws exception, add error code 37 to error list and return result.
    c) If originator is present, go to step C.
    C. Check flag UncodedFlag =’N’,
    a) If no, return result.
    b) If it throws exception, add error code 37 to error list and return result.
    c) If Un-coded=’N’ is present, go to step d .
    d) Check Approver's Staff No is valid,
    If it not valid add error code 31 to error list and return result.
    If it throws exception, add error code 37 to error list and return result...Please explain me detaile
    Thanks in Advance..

    A.Use SQL view to get details
    B. Check originator’s existence
    a) If it not present, add error code 30 to error list and return result.
    b) If it throws exception, add error code 37 to error list and return result.
    c) If originator is present, go to step C.
    C. Check flag UncodedFlag =’N’,
    a) If no, return result.
    b) If it throws exception, add error code 37 to error list and return result.
    c) If Un-coded=’N’ is present, go to step d .
    d) Check Approver's Staff No is valid,
    If it not valid add error code 31 to error list and return result.
    If it throws exception, add error code 37 to error list and return result...Please explain me detaile
    As per the above, are B. Check originator’s existence
    and C. Check flag UncodedFlag =’N’,
    and d) Check Approver's Staff No is valid,
    are remote calls or another webservice ?
    Thanks,
    Vijay

  • Please Explain the sequencer ( J2EE Code )

    Hi,
    The following code is a part of Dao, I could understand the flow of the Dao classes but I really could not make out why this sequencer program is used.
    Please explain and send any URL which will help.
    Comments Plz.
    package lrnsource.src.com.lrn.dao.common;
    import java.sql.Connection;
    import java.sql.SQLException;
    * The Sequencer class represents the oracle
    * implementation of Sequencer.
    public interface Sequencer {
         * Gets the next number in sequence for the given entity.
         * @param entity the given entity.
         * @param con the connection object.
         * @return Returns the next number in sequence.
         * @exception throws SQLException when some problem with DB.
         public long getNextSequenceNumber(String entityName, Connection con) throws SQLException;
         * Gets the current number in sequence for the given entity.
         * @param entity the given entity.
         * @param con the connection object.
         * @return Returns the current number in sequence.
         * @exception throws SQLException when some problem with DB.
         public long getCurrentSequenceNumber(String entityName, Connection con) throws SQLException;
    package lrnsource.src.com.lrn.dao.common;
    import com.lrn.common.CommonConstants;
    * This class provides instance of sequencer
    public class SequencerFactory {
         * Public method which gets the runtime implementation class
         * for implementing the sequence generation related functions
         * @Param          seqType the sequencer type.
         * @return Sequencer interface, the type of implementation class.     
         public static Sequencer getSequencer(int seqType){
              Sequencer sequencer = null;
              switch (seqType) {
                   case CommonConstants.ORACLE_SEQUENCER:                    
                        sequencer = new GemsOracleSequencer();                          
              return sequencer;                    
    package lrnsource.src.com.lrn.common;
    * This class contains the constants used across lrn.
    * <p>
    public class CommonConstants {     
         public static final int ORACLE_PERSISTENCE                    = 1;
         public static final int ORACLE_SEQUENCER                    = 1;
         public static final String DATASOURCE_JNDI                    = "java:/comp/env/jdbc/GemsDB";
         public static final String ERROR_MESSAGES                    = "";
         public static final String CERTIFICATION_SERVICE          = "java:/comp/env/ejb/certification";
         public static final String QUESTION_SERVICE                    = "java:/comp/env/ejb/question";
         public static final String REGISTRY_SERVICE                    = "java:/comp/env/ejb/registry";
         public static final String ADMIN_USER                         = "ADMIN";
    }

    dear friend,
    please look here:
    http://help.sap.com/saphelp_47x200/helpdata/EN/c1/416a55de2a11d3b4ff006094b9b9dd/frameset.htm
    regards,

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

  • 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

Maybe you are looking for

  • Windows 7 and WRT54GS2 connectivity problem

    I have a WRT54G2s router - I currently have a XP laptop and Brother printer working wirelessly with this router.  I received a new computer that is running windows 7.  I can see the router at full strength and am able to connect to it but once I conn

  • QTY in return order more than billed QTY

    hi i am trying to rasie an return order with ref to billing doc and copying the quantity. Though the qty is getting copied from ref doc,i am able to increase the qty more than billed. the system is through an waring msg ,but allowing me raise the ret

  • Organizing music for iTunes/ipod- help

    Example, I have several Tom Petty songs. However, 3 songs are in one place, 1 song in another place, 7 songs in another place. SO.. when I go to play all my Tom Petty, and I hit the Tom Petty song that is in a separate folder it will auto stop after

  • Problems with support

    Hi, my problem is support Apple, I have sent for repair my ipod 4gb ,after many days they have sent back to me a new ipod but 2gb !!! they are days that telephone but I do not succeed to having one answer !!!! I believed that Apple was one serious co

  • IMovie fails to launch

    I installed a new hard drive in my MacBook (late 2007 model) and installed the OS and software from the DVDs. Everything runs great except iMovie and iDVD. When I click on the iMovie icon in the dock, or click on iMovie in the list in Finder>Applicat