Min,Max for a time Range and Sum of Records for the last date/time

Hi All,
I have a table with the following structure/data:
create table  Events   (
                                    [EventID]       
int                   NOT NULL,
                                    [Title]            
nvarchar(200)  NOT NULL,
                                    [SourceName]  nvarchar(20)    NOT NULL,
                                    [Type]             
int                  NOT NULL,
                                    [eDate]           
datetime
insert into Events values(100, 'Event 1', 'S01', 3,'2014-01-01 00:00:00.000')
insert into Events values(100, 'Event 1', 'S07', 3,'2014-01-01 00:00:00.000')
insert into Events values(100, 'Event 1', 'S08', 3,'2014-01-01 00:00:00.000')
insert into Events values(100, 'Event 1', 'S09', 3,'2014-01-01 00:00:00.000')
insert into Events values(101, 'Event 2', 'S010', 3,'2014-01-01 00:00:00.000')
insert into Events values(102, 'Event 3', 'S03', 3,'2014-01-01 00:00:00.000')
insert into Events values(100, 'Event 1', 'S04', 3,'2014-01-01 00:00:00.000')
insert into Events values(101, 'Event 2', 'S05', 3,'2014-01-01 00:00:00.000')
insert into Events values(102, 'Event 3', 'S06', 3,'2014-01-01 00:00:00.000')
insert into Events values(100, 'Event 1', 'S01', 3,'2014-02-01 00:00:00.000')
insert into Events values(101, 'Event 2', 'S02', 3,'2014-02-01 00:00:00.000')
insert into Events values(102, 'Event 3', 'S03', 3,'2014-02-01 00:00:00.000')
insert into Events values(100, 'Event 1', 'S04', 3,'2014-02-01 00:00:00.000')
insert into Events values(101, 'Event 2', 'S05', 3,'2014-02-01 00:00:00.000')
insert into Events values(102, 'Event 3', 'S06', 3,'2014-02-01 00:00:00.000')
insert into Events values(100, 'Event 1', 'S01', 3,'2014-03-01 00:00:00.000')
insert into Events values(101, 'Event 2', 'S02', 3,'2014-03-01 00:00:00.000')
insert into Events values(102, 'Event 3', 'S03', 3,'2014-03-01 00:00:00.000')
insert into Events values(100, 'Event 1', 'S04', 3,'2014-03-01 00:00:00.000')
insert into Events values(101, 'Event 2', 'S05', 3,'2014-03-01 00:00:00.000')
insert into Events values(102, 'Event 3', 'S06', 3,'2014-03-01 00:00:00.000')
And I wrote the following query:
 select EventID as [Event ID],
       Title, 
       count(distinct(SourceName)) as [Instances], 
       Type,
       min(eDate) as  [First Detected],
       max(eDate) as [Last Detected],
       datediff(d,min(eDate),max(eDate)) as [Delta (days)]
from  Events
where type = 3
group by EventID, Title, Type
having max(eDate) <> min(eDate)
   and max(eDate) =(select top 1 eDate from Events order by eDate desc)
and I get the following results (see the instance number)
Event ID Title         Instances Type First Detected                      Last Detected                    
   Delta (days)
=============================================================================================================================
100         Event 1         5         3    2014-01-01 00:00:00.000     2014-03-01 00:00:00.000    
59
101         Event 2        
3         3    2014-01-01 00:00:00.000     2014-03-01 00:00:00.000     59
102         Event 3        
2         3    2014-01-01 00:00:00.000     2014-03-01 00:00:00.000     59
This is normal for this query however what I need to do is a little different.
In other words, while I need to show when we recorded a specific event first and last time,
I need to display the results for the last date/time when it was recorded. 
For example what I need to provide should look like this:
Event ID  Title                Instances        Type       First Detected                    
Last Detected                          Delta (days)
=============================================================================================================================
100         Event 1            2                   3           
2014-01-01 00:00:00.000     2014-03-01 00:00:00.000      59
101         Event 2            2                   3           
2014-01-01 00:00:00.000     2014-03-01 00:00:00.000      59
102         Event 3           
2                   3            2014-01-01 00:00:00.000     2014-03-01 00:00:00.000     
59
Could you please help me to fix this query?
TIA,
John

;With cte As
(Select EventID as [Event ID],
Title,
SourceName,
Type,
min(eDate) Over(Partition By EventID, Title, Type) as [First Detected],
max(eDate) Over(Partition By EventID, Title, Type) as [Last Detected],
eDate,
datediff(d,min(eDate) Over(Partition By EventID, Title, Type),max(eDate) Over(Partition By EventID, Title, Type)) as [Delta (days)],
max(eDate) Over() As MaxEDate
from Events
where type = 3)
Select [Event ID],
Title,
COUNT(Distinct SourceName) As Instances,
Type,
[First Detected],
[Last Detected],
[Delta (days)]
From cte
Where eDate = MaxEDate And [First Detected] <> [Last Detected]
Group By [Event ID],
Title,
Type,
[First Detected],
[Last Detected],
[Delta (days)];
Tom
P.S. Thanks for providing the DDL and data.  That is always very helpful.

Similar Messages

  • I am having a lot of trouble downloading itunes.My latest error message is that MediaToolbox.dll is missing. I have been trying to fix this for three days now .And it all started with the last update .Can anyone help?

    I am having a lot of trouble downloading itunes.My latest error message is that MediaToolbox.dll is missing. I have been trying to fix this for three days now .And it all started with the last update .Can anyone help?

    Taken at face value, you're having trouble with an Apple Application Support program file there. (Apple Application Support is where single copies of program files used by multiple different Apple programs are kept.)
    Let's try something relatively simple first. Restart the PC. If you're using Vista or 7, now head into your Uninstall a program control panel, select "Apple Application Support" and then click "Repair". If you're using XP, head into your Add or Remove Programs control panel, select "Apple Application Support", click "Change" and then click "Repair".
    If no joy after that, try the more rigorous uninstall/reinstall procedure from the following post. (If you've got XP, although the procedure is for Vista and 7, just read "Computer" as "My Computer", read "Uninstall a program control panel" as "Add or Remove programs control panel" and assume the system is 32-bit, and you'll be doing the right things.)
    Re: I recently updated to vista service pack 2 and I updated to itunes 10.2.1 and ever

  • Itunes it's not showing me the last date/time the iPhone/iPad was backed up.

    I just backed up my iPhone and iPad but  iTunes it's not showing me the last date/time my device was backed up. I had just done a backup about 3 hours ago. And when I go to check the backup location I see a folder there with the time it was last backed up. But it's not showing me the backup date in iTunes. I don't know what to do.
    I already tried to remove the folder in App. Support-Mobile Sync and start a brand new backup. But no date.
    Tried to delete and start a new iTunes folder in Music but nothing has changed
    Any solution is welcome!

    iCloud requires OS X Lion (10.7.2) or higher.  You will need to upgrade to either Lion higher in order to set up iCloud on your Mac.  First check to see if your system meets the system requirements to upgrade.
    Lion system requirements are:
    Mac computer with an Intel Core 2 Duo, Core i3, Core i5, Core i7, or Xeon processor
    2GB of memory
    OS X v10.6.6 or later (v10.6.8 recommended)
    7GB of available space
    Mountain Lion requirements are shown here: http://support.apple.com/kb/HT5444.
    Mavericks requirements are shown here: http://support.apple.com/kb/HT5842.
    If you can run Mavericks, you can purchase an upgrade from the Mac App Store.  If you can only run Lion or Mountain Lion, contact the online store in your country and purchase a redemption code to download it from the Mac App Store.
    After upgrading, you will find iCloud in System Preferences>iCloud on your Mac, and can set it up as explained here: http://www.apple.com/icloud/setup/mac.html.
    Before upgrading, you may want to check the compatibility of your existing programs by checking here: http://roaringapps.com/apps:table.

  • When I close Firefox I choose Save and Quit to save my tabs for next opening. It's not saving them the last few times, wondering why?

    Upon closing Firefox it asks me if I'd like to save and quit, quit, or cancel. I always choose save and quit. I've noticed the last few times that my tabs were not saved the next time I opened Firefox, I'm wondering why. I've lost some webpages I was saving for later now, because of this.

    The computer crashes, due to power failure, with Firefox running. After rebooting, Firefox has lost record of tabs. [History/Recently Closed Windows] is grayed out. So the list of tabs is lost. It should be possible for the software to keep a periodic backup of current tabs, such as, e.g., MS Word makes backups of the current file every 10 minutes, so that the tabs can be restored if the software does not make a normal exit due to a computer crash.

  • I install a time capsule and I have to solve the last thing bsGN and it asks me for "a value for bsGN is required", I have no idea what it means. Somebody who knows what to do here? Thank you.

    H E L P !
    I am installing a time capsule and I have to solve a  last problem, bsGN and the system asks for "a value for bsGN is required", I have no idea what that means. Can anybody help me please? Thank you.

    There is no value bsGN in a Time Capsule.
    Where is this request coming from?
    Please give a screenshot.
    Who is the ISP? What kind of modem is it?
    I can find no info relevant to bsGN .. you will need to give us specifics or ring your ISP about it.
    Is bsGN even English?? Is it the ISP name??

  • How to find out the last date & time on which a program has been run

    Hi Experts,
    Can anybody tell how to find out the last date on which a purticular program has been run.
    Valuable answers will be rewarded.
    Thanks & Regards,
    Satish.

    Hi!
    Try STAD transaction. Unfortunately it contains a huge amount of data, so it is available only for a few days backwards... Maybe some weeks, but you can't make yearly reports from its data... So it's not useful to see, which program is in use or not...
    I planned once to download it weekly, but it was not so important...
    Regards
    Tamá

  • Date / Time In SAP ... is it the server Date / Time ?

    Hi,
    If my understanding is all right, the date/time in SBO application is the date/time on the server...
    If I have many offices in the world and they wish to manage BP activities... Does that mean that the reminders will come
    up when the SERVER will be at the date / time of the activity and not when the local time will be the time of the activity ?
    Can I change the way things work  ?
    I've been told that the whole issue of time zones was discussed and this is resolved in the next release 8.8.  But Of course, it does not help right now...
    Do you think there is a workaround by the time we get upgraded to 8.8... ?
    thanks,
    Luce

    You are right, the date/time in SBO application is the date/time on the server.  As for the topic, you may check this thread:
    Re: Time Zone Differenz between users and SQL Server (Citrix)
    Thanks,
    Gordon

  • Ei just paid for Adobe Acrobat Pro and I can not download the program, verytime i go to down load it tells me it doesn't download in my language which is english?why is this program I ordered not letting me download

    i just paid for Adobe Acrobat Pro and I can not download the program, every time i go to down load it tells me it doesn't download in my language which is English? why is this program I ordered not letting me download

    http://www.howtogeek.com/120277/how-to-install-flash-on-the-nexus-7-and-other-jelly-bean-devices/
    You do not need a Beta channel build of Firefox (which currently is 32.0b6) to use Flash as the issue was you needed Firefox 27.0 or newer to use the old Flash 11.1 plugin on Android '''4.4'''. after it came out on tablets/phones.
    What Nexus 7 version do you have as there was a 2012 and a 2013 model. A easy way to tell if it is a 2013 is it has a camera on each '''back''' and front while 2012 only has one on front.
    If it is the 2012 then it has a Nvidia Tegra 3 so the old Flash 11.1 Plugin is disabled.
    For reading only as Bugzilla is not a discussion forum or for "me too" comments.
    *[https://bugzilla.mozilla.org/show_bug.cgi?id=968219 Bug 968219 - flash does not work on Nexus 7]
    *[https://bugzilla.mozilla.org/show_bug.cgi?id=957694 Bug 957694 - Hang/deadlock with Flash on 4.4 on Tegra3]

  • Need to display/update last date/time of an accessed record

    Hi All,
    I'm using ADF BC and I have a use case where I need to display the last date/time when a user access a record in a view. I have a user table that I access thru a view object where I can store the date/time of the fetched record. A viewLink from that view object gives me the detail information in that record.
    I generated a ViewRowImpl class and added this to the method that get the time and date (DtHeureDernAcces is a private variable in defined in the class):
    /**Gets the attribute value for the calculated attribute DtHreDernAcces
    public Date getDtHreDernAcces()
    if (DtHeureDernAcc==null)
    DtHeureDernAcc=(Date) getAttributeInternal(DTHREDERNACCES);
    setDtHreDernAcces(new Date(new java.sql.Timestamp(System.currentTimeMillis())));
    getApplicationModule().getTransaction().commit();
    return DtHeureDernAcc;
    This works fine until the user refresh the page, in this case the ViewObjImpl is recreated and DtHeureDernAcc is then null. So the date/time is updated after each refresh.
    How can I get around this problem ?

    The complication here is that &P7_DATE_SHIPPED. and &P7_DATE_ORDERED. are session-state variables - they don't actually get updated until the page submit completes, which is happening AFTER the dynamic action.
    JavaScript might provide an alternative method that will pick up the current values of those fields. You might try something like:
    HTML Header
    <script language="JavaScript" type="text/javascript">
    function check_hours(pThis){
      var v_shipdt = $v("P7_DATE_SHIPPED");
      var v_ordrdt = $v("P7_DATE_ORDERED");
      if(v_shipdt > v_ordrdt){
        alert("Shipping Date is before Order Date!");
      return true;
    </script>Put this in the HTML Form Elements Attributes of your page item:
    onchange="check_hours(this)"This is just pseudocode, but it may help get you started. Dates in JavaScript are a little tricky to deal with.

  • Getting an error while activating a planning area "Enter values for planning horizon From and planning horizon To for the storage time profile level"

    Dear S&OP community,
    I am getting following error while creating a planning ares in a newly installed sandbox. "Enter values for planning horizon From and planning horizon To for the storage time profile level".
    This what I did...
    1) Created new attributes and master data objects and activated them successfully.
    2) Time profile created and activated successfully
    3) Trying to create planing area by assigning  time profile in step 2 and assigned master data from step1..Unable to save the data and system returns 
    this error - "Enter values for planning horizon From and planning horizon To for the storage time profile level"
    My understanding is time profile needs to be active  but doesn't have to have values...
    Any help is appreciated.
    Thanks,
    Krishna

    YS,
    Here are my time profile settings
    Level       Name          Display Horizon - Past  Display Horizon - Future
    1             Monthly     -6                                       11         
    2             Quarterly     -2                                       3
    3             Yearly        -1                                       2
    Time profile is active and but time profile data is not loaded
    Thanks,
    Krishna

  • Can I view photos and movies from my external hard drive? I used Time Machine and a WD Passport for backup. Since my drive on my MacBook Pro is filling up I was planning to delete some of the movies and photos.

    Can I view photos and movies from my external hard drive? I used Time Machine and a WD Passport for backup. Since my drive on my MacBook Pro is filling up I was planning to delete some of the movies and photos. I wanted to see if I could view them from the hard drive. Thanks

    Hello, eco1. 
    Thank you for visiting Apple Support Communities. 
    This sounds like you are wanting to move your iTunes media folder to an external drive and have iTunes this folder from this location.  If this is the case then I would recommend taking a look at the article below. 
    iTunes for Mac: Moving your iTunes Media folder
    http://support.apple.com/kb/ht1449
    Cheers,
    Jason H. 

  • I bought an ipod in 2006 and used it only for a few days, and i lost it when it fell two times from my hand and it wasn`t working, help me regarding this.

    i bought an ipod in 2006 and used it only for a few days, and i lost it when it fell two times from my hand and it wasn`t working, help me regarding this.
    REGARDS
    RISHABH AULIYA

    Apple - Support - iPod - Repair pricing - http://www.apple.com/support/ipod/service/prices/
    ipod repair options - https://discussions.apple.com/thread/3900047 and https://discussions.apple.com/message/18867033
    Service Answer Center - iPod - http://support.apple.com/kb/index?page=servicefaq&geo=US&product=ipod  <-- enter correct country once on page.

  • Is anyone else having the finish rub off of the keys on their macbook? I've had mine for about 6 months and several keys look like the finish is wearing through. I went to the local genius bar today and the techs said they'd never seen this before.

    Is anyone else having the finish rub off of the keys on their macbook? I've had mine for about 6 months and several keys look like the finish is wearing through. I went to the local genius bar today and the techs said they'd never seen this before.

    Some people have seen their aluminum uni-body discoloring due to body oils.  Go figure.
    Normally putting anything over the keys/aluminum will hurt heat disspation, but you may need to use keyboard covers.
    Or save up $500/year for new keyboards.
    Neither is supposed to be a sarcastic answer.  Either one could end up being the solution.
    Good luck with it.

  • I bought an album on iTunes and 3 of the songs only play for 30 seconds. I have tried re-downloading the album 3 times and the problem has not been fixed. I would like some help please and thank you.

    I bought an album on iTunes and 3 of the songs only play for 30 seconds. I have tried re-downloading the album 3 times and the problem has not been fixed. I would like some help please and thank you.
    Artist: Imagine Dragons
    Album: Night Vision

    Report it here:
    iTunes Store Support
    http://www.apple.com/emea/support/itunes/contact.html

  • How can I enlarge the "all-day" screen on the iPhone calendar?  I use the all-day screen for all my tasks, and it only shows 2 items at a time!!  Help!!!

    How can I enlarge the "all-day" screen on the iPhone calendar?  I use the all-day screen for all my tasks, and it only shows 2 items at a time!!  Help!!!

    The iPhoto App can select all of the photos in the All Imported folder and delete them.

Maybe you are looking for

  • Changing the Datasource of example CMP from Weblogic

    I got an error message while running a successfully (?) deployed Weblogic example bea\weblogic700\samples\server\src\examples\ejb20\basic\containerManaged. The error message is like this when I run the "ant run": run: [java] [java] Beginning containe

  • Finding the no. of occurence of a particular word in a paragraph.

    Hi If I have a paragraph in a string, and have to find the occurrences of a particular word. How can I do that. for example if i have this paragraph in a String, and I have to find the occurrence of the word "the", how can I do that. Paragraph: Despe

  • How can we create a session variable in OAF

    Hi All, i have a Master and detail page. In Master Page I am searching based on Deptno. suppose i enter Deptno 10, i got the 10 th deptno infomation and i click on the Detail Button i went to the detail page and is showed the Details of Deptno. in de

  • I cloud

    I have a iPhone 5 and ipad mini with cellular. Whatever I do on one device like mail calendar notes reminders and surfing I want that it should be possible to continue and duplicate in other device .how do I achieve it .?i have I cloud on both.

  • Restoring Entire System

    My four-year-old hard drive (250gig) crashed.  I have purchased and installed a Seagate Momentus Hybrid (750gig).  I have partitioned it for the "Macintosh HD."  I have booted from a USB flash drive with OSX Lion on it. My question is, do I need to r