SQL Select Records in a range but Not in another range

Dear All
I would like to know the best method to do the following task.
There are records of meeting room usage
room                        start_time
Room A                2014-08-30 16:55:00.000
Room C                      2014-08-30 13:20:00.000
Room B                      2014-08-29 21:45:00.000
Room A                      2014-08-29 22:00:00.000 
I would like to get the rooms used at a range (e.g. 2014-08-30) but cannot be used in another range (e.g. 2014-08-29 or before)
The result should be Room C only.
My apporach is as follows
SELECT room FROM RoomUsage
WHERE start_time >= '2014-08-30 00:00:00' AND start_time <= '2014-08-30 23:59:59'
AND room NOT IN (
SELECT room FROM RoomUsage
     WHERE start_time < '2014-08-30 00:00:00'
Is there any better and simple approach to achieve the same result?
Thank you
Best Regards
swivan

I tend to use EXCEPT or NOT EXISTS for this kind of thing as I find them more intuitive.  I also tend
not to use Not In for JOINs due to its well-known problem with NULLs, ie if there is a NULL in the inner resultset the query short-circuits and you get no records.  I therefore prefer to use In / Not In for
short lists eg Not In ( 'a', 'b', 'c' ).
See for yourself:
IF OBJECT_ID('tempdb..#roomUsage') IS NOT NULL DROP TABLE #roomUsage
CREATE TABLE #roomUsage ( room VARCHAR(20) NOT NULL, start_time DATETIME2 NOT NULL )
INSERT INTO #roomUsage
VALUES
( 'Room A', '2014-08-30 16:55:00.000' ),
( 'Room C', '2014-08-30 13:20:00.000' ),
( 'Room B', '2014-08-29 21:45:00.000' ),
( 'Room A', '2014-08-29 22:00:00.000' )
SELECT room
FROM #roomUsage
WHERE start_time >= '2014-08-30 00:00:00' AND start_time <= '2014-08-30 23:59:59'
EXCEPT
SELECT room
FROM #roomUsage
WHERE start_time < '2014-08-30 00:00:00'
SELECT room FROM #roomUsage
WHERE start_time >= '2014-08-30 00:00:00' AND start_time <= '2014-08-30 23:59:59'
AND room NOT IN (
SELECT room FROM #roomUsage
WHERE start_time < '2014-08-30 00:00:00'
-- Oops
SELECT room FROM #roomUsage
WHERE start_time >= '2014-08-30 00:00:00' AND start_time <= '2014-08-30 23:59:59'
AND room NOT IN (
SELECT room FROM #roomUsage
WHERE start_time < '2014-08-30 00:00:00'
UNION ALL
SELECT NULL

Similar Messages

  • Selecting records from multiple dates but specific time

    Hi:
    I've to select records of multiple dates but the time should be 00:00:00 to 06:00:00 (i.e. 12 AM - 6 AM)
    For date part this can be done:
    WHERE
    START_TIME BETWEEN TO_DATE('04-01-2012', 'MM-DD-YYYY') AND TO_DATE('04-05-2012', 'MM-DD-YYYY')
    But how can I fix the time mentioed above.
    Please let me know.
    Thanks/Tanvir

    WHERE
    START_TIME BETWEEN TO_DATE('04-01-2012', 'MM-DD-YYYY') AND TO_DATE('04-05-2012', 'MM-DD-YYYY')
    and start_time - trunc(start_time) between 0 and 6/24start_time - trunc(start_time) will give you the fraction of a day. So 6/24 means 06:00.
    (When you use to_char(trunc(sysdate,'hh'),'hh24') between 0 and 6 you will also retrieve records with start_time 06:01 for example. So this would not meet your requirements as far as I understood.)
    Edited by: hm on 10.04.2012 01:26

  • Why is my iPhoto library greyed out in the Screensaver folder selection dialog on one iMac but not my other?

    Why is my iPhoto library greyed out in the Screensaver folder selection dialog on one iMac but not my other?

    I have an update to my issue above, with a Semi-solution found. I brought my Macbook Air back to the Genus bar today and they were able to identify (using “Activity Monitor”) that when the particular iPhoto library was being launched through iPhoto both Photostream and iPhoto's CPU% usage was excessively high (between 100% - 200% each). She discovered that if we turn off Photostream in iCloud settings iPhoto then behaved fast and snappy and CPU% came back down to a healthier level. When we turned Photostream back on the problem continued. After an hour of trying to trouble shoot why Photostream was causing the issue they recommended I keep Photostream turned off until a future software update/fix comes out. The particular Genus I worked with was not familiar with this issue. I’m very happy to at least be able to use iPhoto again, but if anyone has ideas or theories on how the Photostream conflict can be fixed please share. Thanks.

  • Airplay works for one user but not for another on the same machine

    I have the problem where airplay works for one user but not for another and both users are on the same machine.  For the user where it does not work, everything appears normal, it's just that there is no sound being transmitted.  I have tried restarting the Airport express, restarting iTunes, repairing disk permissions.  Any ideas about what can be done to resolve this?

    my /etc/group:
    root::0:root
    bin::1:root,bin,daemon
    daemon::2:root,bin,daemon
    sys::3:root,bin
    adm::4:root,daemon
    tty::5:
    disk::6:root
    lp::7:daemon
    mem::8:
    kmem::9:
    wheel::10:root,hans,ibm,gast
    ftp::11:
    mail::12:
    uucp:x:14:
    log::19:root
    locate:x:21:
    smmsp::25:
    http::33:
    games::50:
    network:x:90:
    video:x:91:
    audio::92:ibm,gast
    optical::93:hal
    floppy:x:94:hal
    storage:x:95:hal
    scanner:x:96:
    power:x:98:
    nobody::99:
    users::100:gast
    dbus:x:81:
    hans:x:1001:
    vboxusers:x:108:hans
    policykit:x:1002:
    hal:x:82:
    kvm:x:78:
    nx:x:85:nx
    avahi:x:84:
    camera:x:97:
    gdm:x:1003:
    gast:x:1004:

  • "SOME" devices can resolve the ALIAS (CNAME record) for a device, but not the REAL name (A record) - Why? How do I fix this?

    I'm running the DNS server role on Windows Server 2012 R2 on a physical machine on my home network.
    My AD is configured with a non-registered name - let's say it's "home.acme.ca" and the DNS server is configured to host that zone.  I also configured a 2nd zone in the DNS server called "myinf.acme.ca".  They both run on a physical
    server with an IP of 192.168.1.10
    The DHCP server on my Cable Modem is configured to hand out 192.168.1.10 as the only DNS server to every device on my network.  On my servers (with static IP addresses), 192.168.1.10 is configured as the only DNS server available for them. 
    I took the DNS servers from my Cable Provider and configured a Forwarder on my server to send name resolution requests to them only if my DNS server can not answer the request - basically for any name resolution request that does not end with ".home.acme.ca"
    or ".myinf.acme.ca"
    The "home.acme.ca" zone is populated with 'A' records for all of the physical and virtual servers and PC's on my network.
    The "myfin.acme.ca" zone is populated with 'CNAME' records that point directly to the 'A' record in "home.acme.ca" - for example, I have a serve named s000abc123ww.home.acme.ca with an 'A' record providing an IP address of 192.168.1.20 and
    I created a 'CNAME' (alias) record named 'webserver.myinf.acme.ca' which points to the 'A' record 's000abc123ww.home.acme.ca'
    2 of my 6 machines can resolve the alias but not the real name of the server!
    .10 is the Domain Controller.  All of the other machines (except .98) are members of the home.acme.ca domain.
    I attempted to ping 's000abc123ww.home.acme.ca' AND 'webserver.myinf.acme.ca' on the following 6 computers.  I used the fully qualified name in all cases.
    4 of the below machines are able to resolve BOTH names.  The other 2 can resolve the Alias but not the real name!
    I don't understand how this is possible, but I would like to fix it...!!!  Please help?
    .10 - Server 2012 R2 (Physical) -  Hosts Active Directory and DNS.
    .20 - Server 2012 R2 (Virtual)   -  Runs SQL Server
    .21 - Server 2012 R2 (Virtual)   -  Runs Apache
    .22 - Server 2012 R2 (Virtual)  -   Runs Apache.  This is the device I am trying to ping (s000abc123ww)
    .98 - Windows 7 (Physical)
    .99 - Windows 7  (Virtual)
    .21 (which is configured nearly identically to .20 and .22) can resolve and ping the Alias, but not the real name.
    .98 can also resolve and ping the Alias, but not the real name.
    The rest of the machines can resolve and ping both the alias and the real name.
    All of the Virtual Machines are running under Hyper-V on the .10 physical server.
    All the devices are on the same subnet.
    Thank in advance to anyone who can help me understand and correct this problem!
    Jim

    Hi,
    CNAME resource records are recommended for use in the following scenarios:
    • When a host that is specified in an A resource record in the
    same zone needs to be renamed
    • When a generic name for a well-known server, such as www, must resolve to a group of individual computers (each with individual A resource records) that provide the same
    service, for example, a group of redundant Web servers
    Therefore please try to create your CNNAM record in the same zone and try again.
    The related KB:
    Adding, Changing, and Deleting Resource Records
    http://technet.microsoft.com/en-us/library/cc779020(v=ws.10).aspx
    Hope this helps.
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • SQL query works in access 2000 but not through JDBC

    Hello to all as my first posted message, I have a bit of a pickle on my hands. I have a query which is critical to for my application to function.
    In Access 2000
    SELECT sb.SeatName
    FROM SeatBooking sb, Movie m, MovieSession ms, Booking b
    WHERE m.MovieId = ms.MovieId
    AND ms.MovieSessionId = b.MovieSessionId
    AND b.BookingId = sb.BookingId
    AND ms.DateOfSession = #2003/04/16 07:15:00 PM#;
    This query works fine. When I insert it into my code
    String query = "SELECT sb.SeatName \n" +
    "FROM SeatBooking sb, Movie m, MovieSession ms, Booking b \n" +
    "WHERE m.MovieId = ms.MovieId \n" +
    "AND ms.MovieSessionId = b.MovieSessionId \n" +
    "AND b.BookingId = sb.BookingId \n" +
    "AND ms.DateOfSession = #" +
    cp.getMovieSessionAt(i).getTrueTimeOfSession() + "#;";
    The last line of code returns #2003/04/16 07:15:00 PM#; Which is the exact same as in Access.
    To rule out some possibilities
    - there are other less complicated queries which access the same database but work fine. so my code seems to be ok
    - I have tried to use Format() on ms.DateOfSession to match the return value of the java statement (Which is a general date in Access in the format of 16/04/2003 7:15:00 PM)
    Any suggestions would be appreciated!

    Hi Simon,
    On my Windows XP system with J2SE SDK version 1.4.1_02 and Micro$oft Access 2002, I have the following table:
    column name    column type
    id             Number
    name           Text
    updated        Date/TimeUsing the JDBC-ODBC bridge driver (that is part of the J2SE distribution), the following code uses the JDBC "escape" syntax -- and it works.
    import java.sql.*;
    public class JdbcOdbc {
      public static void main(String[] args) {
        Connection dbConn = null;
        ResultSet rs = null;
        Statement stmt = null;
        String sql =
          "SELECT * FROM Table1 WHERE updated = {ts '2003-04-13 07:53:23'}";
        try {
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          dbConn = DriverManager.getConnection("jdbc:odbc:db1");
          stmt = dbConn.createStatement();
          rs = stmt.executeQuery(sql);
          if (rs.next()) {
            System.out.println("id      = " + rs.getInt(1));
            System.out.println("name    = " + rs.getString(2));
            System.out.println("updated = " + rs.getTimestamp(3));
        catch (SQLException sqlEx) {
          System.err.println("Database operation failed.");
          sqlEx.printStackTrace();
        catch (ClassNotFoundException cnfEx) {
          System.err.println("JDBC driver class not found");
          cnfEx.printStackTrace();
        finally {
          if (rs != null) {
            try {
              rs.close();
            catch (SQLException sqlEx) {
              System.err.println("ERROR: Failed to close result set");
              sqlEx.printStackTrace();
          if (stmt != null) {
            try {
              stmt.close();
            catch (SQLException sqlEx) {
              System.err.println("ERROR: Failed to close statement");
              sqlEx.printStackTrace();
          if (dbConn != null) {
            try {
              dbConn.close();
            catch (SQLException sqlEx) {
              System.err.println("ERROR: Failed to close DB connection");
              sqlEx.printStackTrace();
    }More details about the JDBC escape syntax are available here:
    http://java.sun.com/j2se/1.4.1/docs/guide/jdbc/getstart/statement.html#999472
    Hope this helps you.
    Good Luck,
    Avi.

  • Is it possible to record slide transition timing but not narrative?

    I'm working on a presentation and will be receiving a recorded audio soundtrack that will need to play for the entire presentation. I figured out how to delay the transitions so I can pace the slides to the soundtrack. However, when I try to export so it is a self-contained movie or flash file, I can't find an option that maintains the different transition delays. It either has to be manual (which isn't what we want) or a fixed timing (which won't work with the soundtrack).
    And if I try to record the timing, it also records the ambient noise in my office. Is there a way to record the timing but not the narration? Or, a way to export with custom delays? For the first showing, the presentation will be able to be run from Keynote, but we want to be able to distribute afterwards as we anticipate people will want to take the presentation back to their companies to share it. Any advice would be greatly appreciated, thanks in advance.

    Welcome to the Forum.
    <<And if I try to record the timing, it also records the ambient noise in my office. Is there a way to record the timing but not the narration? >>
    Go to the System Preferences > Sound > Input menu and select Line In. Then set the Input Volume control to zero. Now you can record with no audio input.
    Good luck.

  • Selecting more than one calendar but not all?

    is it possible on the iTouch iCal application to view more than one calendar but not all? I have one calendar that I would like to have available, but when I check for conflicts, that calendar doesn't matter (if it were included, every day would be a conflict).
    I don't see any way to do this, but I am hoping someone has a workaround or other solution.
    Charles

    Let's say I have three calendars: Home, Business, and Daily Junk. The Daily Junk calendar serves as a type of to-do list (and yes, I know there's a separate todo list -- this is an example). I want to see a view that shows Home and Business at the same time, but not Daily Junk. I can view all -- which gets Daily Junk -- or I can view Home or Business, but not Home and Business but not Daily Junk.
    Am I missing something obvious? When I select a specific calendar, I don't have an option to do more than one -- I get a specific calendar or all of them.
    Thanks much

  • Selective Mode Pubshing (See it but NOT Try it, etc.)

    I am trying to publish player content for my partner organization. They would like the "SEE IT" and "PRINT IT" but not the other modes. When I publish, I always get ALL the player modes.
    Looking at the topic properties, it appears as though you can check some rather than all modes. But when I publish, all modes are published regardless.
    I tried to provide a link to only the "SEE IT" content but it required a player package. I tried this out on a machine and ran the installer for the player package. It still brought me to a page with all the other modes on there.
    Surely there must be a way to selectively publish. Cannot find in any resolution in my UPK documentation.
    es
    Edited by: 922588 on Mar 21, 2012 2:59 PM

    Hi es,
    I managed to get my UPK 11 to only show "See It", "Try it" and "Print it". It seems like 'Try it" is hand-in-hand with "See it", so I could therefore not get rid of "Try it".
    As you have done, ensure that "See It/Try it" is selected as the mode for EACH frame within the topic - this is changed in the "Show in" block under the Frame Properties.
    Then, when you publish, you must change some options too. Get to the stage of the publishing wizard where you have the tick boxes available to you to choose what and how to deploy content. Select the "Player and LMS" option, and look at the properties on the right. Under Player Preferences, ensure that the default mode is "See It". On the same properties, further down, there is a section called "Print It" - ensure that the Text Mode "See It/Try It" is selected here.
    Then, on the left again, choose the option that says "Standalone Topic Files" - preview the properties, and again, ensure that the Text Mode under "Print It" is set to "See It/Try It".
    Go ahead and publish - you may get errors as I did, stating that there is no "Do It" mode etc. This is fine.
    Preview the play.exe and then see if that is what you want?
    Best I could come up with - hope it helps somewhat!
    Regards,
    Greig

  • Selectively enable push notifications calendar but not email?

    Is there a way to only enable push notifications for my calendar (Google Calendar through iCal), but not my email (Gmail account in Mail.app)? I want the Mail.app to be setup for Gmail when I want to send email links from apps, etc., but I don't want constant push notifications (otherwise I'd just use the Gmail app). I turned off the Notifications for Mail.app, but the phone still vibrates when a new email comes in.

    You're confusing at least 4 different things, - push email, push notifications, notifications and alerts,
    "Push notifications" are what certain 3rd party apps use to remotely send info to you.
    "Push Email": IMAP and Exchange accounts that automatically send mail to the phone.
    "Notifications":  Internal text type alerts when certain events occur such as receipt of mail (push or fetch)
    "Alerts": Tones and/or vibrations when an event occurs
    The best I can determine from your post is that you're getting unwanted vibrations when receiving push mail - no other notifications.  If that's the case, in iOS 6 (coming 9/19);
    Settings > Sounds > New Mail > Vibration > None

  • IPod recognized on one PC, but not on another

    Hi!
    I just received a brand new iPod Click Wheel 20GB in exchange for my old one that had a hardware defect within the warranty period.
    When I tried to connect the device to PC1 (WinXP) which I had always used with the old iPod without any problems, the new iPod was discovered in Windows, but not in iTunes, although the diagnostics feature in iTunes showed the iPod connection with a green "light".
    I removed all other USB devices, re-installed iTunes 7.0.2. twice, reset the iPod a few times and also put it into disk mode. After some attemps, it was recognized by iTunes and started to synchronize songs (which are both imported from original CDs and purchased from iTunes). However, synchronization took a lot longer than it used to with the old iPod (approx. one song per minute now compared to one song per 5-10 sec. before). After some time (3GB in first try, 7 GB in second try) an error code ("1-24") was displayed and synchronization (which should have been 18 GB in total) stopped.
    The next thing I did was to try to connect the iPod to PC2 (again WinXP), first using an older version of iTunes and a different library. It worked without problems. Then I upgraded iTunes to V.7.0.2. and it still worked. Then I copied the iTunes library from the PC1 to PC2 and again, it worked.
    In connection with copying the iTunes library, another question emerged: I copied all folders unter \iTunes\iTunes_Music from PC1 to PC2. Strangely, only 1,500 songs were copied on PC2, while there are over 3,000 songs on PC1. I compared the directories in detail and found out that there were artists with and some without their own directory, which might be the reason for the difference, as songs of those artists had not been copied.
    Hence, my questions to the community are:
    - What could I do to make the connection of my iPod with PC1 work like it did with the old iPod and like it does on PC2?
    - Where is the rest of the songs/artists that do not have a seperate directory?
    Thanks for your help, cheers, Boern.

    I have the same kind of problem. I installed the ipod on one comouter in my house, dont know what version of itunes but i dont think the latest one and registered it, then I installed it onto this pc with the latest version of itunes and windows dosemt recognise it. It makes me insall drivers like five times and sends me loads of messages saying things like it is installed and ready to use one minute, then found new hardware the next. And even now after I have installed everything and I dont get the messages anymore it still dosent come up in 'my computer.' Does anyone know what the problem could be?

  • Office 2008 Setup Assistant Loop for one user, but not for another

    I just upgraded my MacBook Pro to a MacBook Air and migrated everything across using Migration Assistant via WiFi.
    Seems to have gone fine but found that my wife can't get any Office 2008 apps to start up. Word, Excel, etc start up in my account without a hitch but when we try to start any Office app in wife's account the Setup Assistant pops up, asks if we'd like to participate in feedback, then asks to choose to register or learn more. No matter what we choose the Microsoft Updater pops up and prompts to check for updates after this the app closes. We are forever in this loop of trying to open an Office app, checking for updates and then the app closing down. And the app closes even if I quit Setup Assistant and/or Microsoft Updater.
    I've tried dumping various plists but not luck.
    Any help in resolving this would be much appreciated.

    Another copy of this question turned up a couple of weeks later and has been answered. Basically, you have to reinstall Office 2008 from the original media.
    https://discussions.apple.com/thread/3645235?start=0&tstart=0

  • DVD plays on one TV DVD player, but not on another

    I made a video for a client's 50th b-day party, and burned it with DVDSP 3.
    I am using Verbatim, DatalifePlus 16x media.
    It plays fine on my G5 and my TV's DVD player, as well as on my clients computer, but not on his TV's DVD player.
    I am not sure what kind of equipment the DJ at his party will use, but of course I want to be confident it will work.
    Anyone have issues like this, or any solutions/explanations?
    Thanks.

    If I was going to wager, it sounds like the player is old.
    The other items can also cause issues, sometimes high rates can cause problems, but it does not sound like that is the case with the rates you used, especially if you (?) used AC3 for the audio. Usually that would happen more if playback is poor (as oppossed to not playing at all.) Also note that some players handle dirt/scratches better than others, so some may play the disc and another may not. Of course the last thing is that it is DVD SP causing the issue. Some players have issues with how DVD SP authors a disc.
    I would try burning slower (as suggessted) and try a different brand of media. If you are able to find out which machine they have you may be able to find out what it is designed to play (media -R/+R etc.) of if there are known issues with the machine. Usually older machines would work with -R if there was going to be one over the other.
    Take a look here
    http://www.digitalfaq.com/media/dvdmedia.htm
    Verbatim seems to be rated well. Personally I like Taiyo Yuden -R for SL and Verbatim +R for DL

  • HT1937 my cellular data connection works in one location but not in another

    Why does my iPhone's data connection work at other places but not at work?
    It works sometimes.

    Good question to ask your cell phone provider.. Maybe the material the building is made of is blocking the cellular data signal.

  • Missing Benefit Plan in HRBEN0001 in one client but not in another.

    Hi All,
    I was wondering if anyone has stumbled upon this issue where your benefits configuration are identical in three clients.  I have configured two savings plans - 401K and Roth which the employee is allowed to make changes anytime.  In two DEV clients, I was able to see both savigns plan in HRBEN0001 and 401K in QA but not the Roth.  I've compared the configuration and the dates and they are correct (and identical). 
    I went back into QA and hired a new test employee and the Roth plan appears in HRBEN0001.  My question is: why didn't the Roth plan appeared for the employees that were previously hired.  Is there a table that needs to be activated in QA? 
    Your help is much appreciated!  Thanks!

    Hi Donna,
    Could you please tell how did you resolve this issue as I am facing same problem. I have configured 3 pension plans which are not reflecting under HRBEN0001. Appreciate your help.
    Regards,
    Purnima

Maybe you are looking for

  • NF-es paradas no R/3

    Olá, Hoje pela manhã estávamos com um problema no ambiente e algumas NF-es foram geradas. Agora que a situação já  voltou ao normal e algumas dessas notas estão com status de em processamento. Quando vamos consultá-las no GRC, não consta nenhum regis

  • Unable to see shared library using fast user switching?

    I couldn't get iPhoto 5.04 sharing to work between two users on a single machine. The documentation and this thread say it should work: lori_diloreto, "How can you share a iPhoto library with another account user" #1, 09:03am May 10, 2005 CDT but it

  • Upgrade to SCM7.0 DP info objects (Characteristics) long/short text issue

    Hi All, We have upgraded from SCM4x to SCM7.0. The info objects characteristics customized long and short text is not updated in SCM 7.0. Example: Info object 9ALOCNO standard long/short text is APO location. But in SCM4x they have changed to Plant.

  • The J2EE Tutorial (Chap 15-Custom Tags in JSP pages

    The definition class "DefinitionTag" talks about putting the definition instance of "Definition" class in a page context, using the following code // put the definition in the page context context.setAttribute(definitionName, definition, context.APPL

  • CRM OnDemand in S&OP Processes

    We are looking to talk with a customer who uses CRM OnDemand as an input into their S&OP - if there is anyone out there using it, please send a note! Thanks!