Cartesian time data across multiple hourly rows

Looking for a solution for exploding time rows into multiple rows by hour. For example, take a row like this:
EventTime         EventLengthSeconds
2014-04-25 13:31:16.857 6657
What I need is multiple rows to allocate the time by hour like this:
EventTime         EventLengthSeconds
2014-04-25 13:31:16 1724
2014-04-25 14:00:00 3600
2014-04-25 15:00:00 1333
I've crafted a solution using a derived table that I cross join to then use case statements, etc. but it's super ugly and I'm embarrassed to post it. 
I'm thinking in SQL 2012 there must be a elegant and efficient way to do this with the new windowing functions that are available. 
Thanks for any insights and suggestions.

You need a table of hours for this problem. The more general concept is a table of numbers. That is, a table that spans the dimension you are working and provides a row for each discrete value.
Below is an example how you can fill the table and then a query which uses this table:
CREATE TABLE Hours (Hour smalldatetime NOT NULL PRIMARY KEY);
WITH digits (d) AS (
   SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION
   SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION
   SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION
   SELECT 0)
INSERT Hours (Hour)
   SELECT dateadd(Hour, Number, '20000101')
   FROM   (SELECT i.d + ii.d * 10 + iii.d * 100 + iv.d * 1000 +
                  v.d * 10000 + vi.d * 100000 AS Number
           FROM   digits i
           CROSS  JOIN digits ii
           CROSS  JOIN digits iii
           CROSS  JOIN digits iv
           CROSS  JOIN digits v
           CROSS  JOIN digits vi) AS Numbers
   WHERE  Number > 0
     AND  dateadd(Hour, Number, '20000101') < '20500101'
DECLARE @eventtime datetime2(3) = '2014-04-25 13:31:16.857',
        @eventspan int          = 6657
SELECT @eventtime AS EventTime,
       3600 - (60*datepart(minute, @eventtime) +
                  datepart(second, @eventtime)) AS EventSeconds
UNION ALL
SELECT Hour,
       CASE WHEN dateadd(second, @eventspan, @eventtime) >
                 dateadd(HOUR, 1, Hour)
            THEN 3600
            ELSE datediff(SECOND, Hour, dateadd(second, @eventspan, @eventtime))
      END
FROM   Hours
WHERE  Hour > @eventtime
  AND  Hour < dateadd(SECOND, @eventspan, @eventtime)
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • I'm typing dates across the top row. I want the date to be 12/13 and the program changes it to Dec. 13. It is making me mad. How do I get it to stop doing the change? I want a numerical number.

    How do I get the numbers program to type a numerical date across the top row? It wants to change it to Dec. 13 instead of 12/13.

    Amy,
    I hope that you can forgive Numbers for converting the date you enter as 12/13 into the default format of "December 13, 2011", one that is popular with many users.
    You can change to any of the supported date formats by using the Cells Inspector, Date and Time options.
    Select the top row of cells and use the inspector to set the format. You may do this before or after making the entries.
    Jerry

  • Sync data across multiple clients

    I am create an application in flex that pulls and pushes data to a MySQL database.  This program will have multiple clients logged in at the same time.  I am wondering what the best way to ensure that the data is accurately updated across all of the clients would be.

    Can you explain what you mean exactly by sockets?
    Is there any way to Sync data across multiple clients without the crazy expensive cost of LCDS?

  • Share data across multiple WAR

    Does somebody know any pattern to share data across multiple WAR applications?
    I need to modularize an Intranet Application?
    So, I don't have to shutdown the entire intranet to make the changes in just one module .
    It is possible to share a session object? or I must to get and propagate browser session id :( ?
    Any idea will be appreciated.

    Yes you can, I did it running tomcat
    -First have to set crossContext propertie value to "YES"
    Then this is my pice of working code :
    javax.faces.context.FacesContext facesContext = javax.faces.context.FacesContext.getCurrentInstance();
    javax.faces.context.ExternalContext externalContext = facesContext.getExternalContext();
    javax.servlet.ServletContext servletContext = (javax.servlet.ServletContext)externalContext.getContext();
    Object yourObject = new Object();
    if(servletContext.getContext("/yourContextName")!=null)
    servletContext.getContext("/yourContextName").setAttribute("yourObject ",yourObject);
    Jesus

  • Moving car at Time/Date for 11 hours

    Hi,
    I'm making a timeline with a moving car. It has to go from left to right in about 11 hours.
    I got this code and the car is moving from left to right:
    import fl.transitions.Tween;
    import fl.transitions.easing.*;
    import fl.transitions.TweenEvent;
    bus.x = 0;
    bus.y = (stage.stageHeight-bus.height)/2;
    var carTween:Tween=new Tween(bus,"x",None.easeNone,300,stage.stageWidth-bus.width,39600,true);
    carTween.addEventListener(TweenEvent.MOTION_CHANGE, onChange);
    function onChange(e:TweenEvent):void {    
    trace(bus.x);
    carTween.addEventListener(TweenEvent.MOTION_FINISH, onFinish);
    function onFinish(e:TweenEvent):void {
        trace("Out of gas, destination complete");
    But everytime I refresh my page the car is at the begin again. So I have to attach it to a Timer/date class to it so it stops at a certain point / time and date.
    Can somebody help me out with that because I cant figure it out how to do it..
    Tnx

    You can have your existing code do that with a little tweaking...
    var StartDatum:Date = new Date(2011, 01, 15, 12, 00, 15, 0);
    var EindDatum:Date = new Date(2011, 01, 15, 15, 45, 15, 0);
    var TotaleTijd = EindDatum.getTime() - StartDatum.getTime();
    var MijnTimer:Timer = new Timer(1000);
    MijnTimer.addEventListener(TimerEvent.TIMER, Detijd);
    MijnTimer.start();
    function Detijd(e:TimerEvent=null):void {   // add =null to argument
         var Nu:Date = new Date();    
         var TijdOver:Number = Nu.getTime() - StartDatum.getTime();
         var Voortgang:Number = TijdOver / TotaleTijd;
         car.x = stage.stageWidth * Voortgang;
    Detijd();  // call it immediately when the program starts

  • Spreading user data across multiple HD's?

    I hope this is the right forum for this. I'm on a Mac Pro 1,1 and recently installed a few extra hard drives to optimize performance for video editing (accoring to recommendations over at another big software company's support docs -- this is not about FCP).
    My goal is to have this general set-up:
    SSD: Boot Drive (OS & Apps) -- already set up
    Disk 2: Editing Project Files, media and exports
    Disk 3: Cache, renders and previews
    Disk 4: Ideally this would be for docs, itunes, photos and anythings non video related.
    The thing is, this advice comes from PC users mainly and the OSX User Folder structure isn't an issue.
    Question: Can the same user folder's contents be spread across multiple HD's? I realize I'll need to physically place a different "house" icon folder in each HD, probably, but can those have different contents? How can I make them all boot on start-up so the disk allocation is pretty much not noticeable?
    Thanks!

    A simple version of what you are trying is to establish a Boot Drive, with only System, Library, Applications, and the hidden unix files. All user files are moved off to a different drive.
    Here are some simple recipes for Moving the "Home" folder"
    Japamac's Blog: Make space for Performance -- Moving the Home Folder
    http://chris.pirillo.com/how-to-move-the-home-folder-in-os-x-and-why/
    You can embellish this basic setup any way you wish, especially putting Movie data on a different drive, and Movie cache data on yet another drive.

  • Duplicate rows and data across multiple pages.

    My form has 12 pages (each page = 1 month). With a loop, the pages are hidden until the corresponding button is clicked and it becomes visible (Thanks Assure Dynamics for a great solution to a very long form).
    In Month 1, I have a table with a repeating row. What I would like to do is copy the repreating row and it's data to Month 2. Then I would like to have the table from Month 2, duplicate to Month 3, Month 3 to Month 4 and so on.
    I have been able to get the row from Month 1 to duplicate in Month 2 on the exit event of each cell in the row, however, when you are in Month 2 and do not change a cell which was created in Month 1, the data does not duplicate into the next month (Month 3). Instead of on the exit event of the cell(field), I thought placing it on a button would work but it is not.
    This is what I used on the exit event in the table for Month 1:
    xfa.resolveNode("Month2.Performancegoals2.updates.details[" + this.parent.index + "]").projectName.rawValue = this.rawValue;
    I also thought instead of using a table and a repeating row, I could place the information in a repeating subform but I am still stuck with how to copy the subform and its completed data to the next month.
    I am really stuck and have been looking for hours for a solution. Can anyone help, I am out of time for the deadline of this form.?

    Hi,
    Firstly,you must do the count of the table.
    frmTableBlock.tblTableMonth2._rowItem.count = frmTableBlock.tblTableMonth1._rowItem.count
    frmTableBlock.tblTableMonth12._rowItem.count = frmTableBlock.tblTableMonth1._rowItem.count
    And write the code which is do you want to copy the data Month1 to month12.
    I hope
    S,Candy

  • Why does a digital indicator formatted for time & date add 16 hours to the input?

    I wire a digital indicator with a double precision value that is supposed to indicate an elapsed time. But the indicator (formatted for time and date, with the date inactive) always adds 16 hours to the wired input.
    This problem occurs even in a simple vi I wrote that only consists only of a constant wired to the indicator.
    Using LabView 6.0.2

    Labview interprets the number passed into an indicator formatted for date & time as seconds since Jan. 1st 1904. I'm assuming that since you're looking for elapsed time this is not what you're passing in. One thing that I've done is get the elapsed time in seconds and write a routine to convert that into whatever format you want.

  • Summarizing Data Across Multiple Dates

    Here is my issues.
    I have two dimensions.
    Date and Time. Date is a standard date dimension. Time is a time dimension who's leaf level is at the second.
    I need the ability to obtain a value like maximum from my fact table for a given set of prices. I want to summarize this value at the day level. The issue is that the value can span across 2 dates.
    Example. A Sunday starts at 4PM and ends Monday at 9AM. I need to obtain the maximum value across these specific times from both Monday and Sunday (at the specified times).
    Effectively, I need MAX(MONDAY at time 12:00AM - 9AM, SUNDAY at time 4PM - 11:59:59PM) to be displayed in the data for Date Monday.
    Suggestions on to approaches for this?

    Guys thanks for your suggestions.  Yes I'll give those options a try...
    Just a pity there was no 'aggregator' type activity which would negate the need to go down the route of writing out to SQL or create master/child runbooks which just seem a bit of overkill or adding complexity esp when using very simple runbooks - like I
    say maybe one for the IP developers out there...
    To illustrate my specific eample (one of many simple runbooks requires a summary email sent out to show output) as below:
    So the first Powershell gets VDI desktop names (3 of them) then 2nd Powershell uses these machine names as published data to get associated registration state.  From there I'd ideally like to just generate out the single summary email showing the 3
    machines/reg states instead of 3 separate emails.  I added the append line and get line activities to expose the output to check it was OK and then tried flattening various activities to try and only generate the single email (I removed the junction activity
    infront of sendmail as it didn't work)
    So I'll try the options suggested for spliiting runbooks and/or writing to SQL and see how that goes..
    Cheers

  • How can split data into multiple sheets using an excel template

    Hi all,
    I'm using BIP 10.1.3.4.1 upgrated with the latest rollup patch, 9546699.
    I followed the example inside the article "Real Excel Templates 1.5" (on the Tim Dexter's blog)
    http://blogs.oracle.com/xmlpublisher/2010/05/real_excel_templates_i.html
    and I built my report directly from an excel template containing only one sheet (plus the XDO_METADATA sheet), and for one sheet it worked fine !!!
    Now I need to add more sheets to the template.... and I have two big questions:
    1. if I need to create a second sheet which contains almost the same data (with a different layout), I saw that it is not possible to map a value to more than 1 cell....so if I map a value in the first sheet, I can't map it in the second sheet (because it's already used in the first one).
    How can I map same values into two or different execll
    2. if I need to create a second sheet which contains another dataset (completely different from the dataset in the first sheet), I can I do, considering that every BIP report is based on ONLY a data source.
    Tim wrote: The most impressive, for me at least, is the sheet 'bursting'. You can split your hierarchical data across multiple sheets and dynamically name those sheets
    but I didn't yet understand how this bursting it's possible.....considering what I said above.....
    Surely I've a lack of knowledge.....but anybody can help me to understanding the "multiple excel sheets" black hole ?
    I'll appreciate any kind of help
    Thanks in advance
    Alex

    You can find working solution here http://xlspe.com

  • Best way to manage date/time variables across different timezones

    I have an application that relies heavily on time accuracy. At the moment everything is fine, but soon the system will service customers across multiple timezones. The default behavior of the Date class is to show dates related to the current timezone, is there an easy way (setting) to override this behaviour? The system should show the time entered regardless of the timezone it was entered on.
    I use CF 8 for the back-end, and MySQL 5.1 to store data. The front-end is Flex 3/Air 2.
    I have looked everywhere, and things like saving dates as strings, or long ints, but if possible, I'd like to find a solution that does not involve dramatic changes to my database/code.

    Thanks for your reply, UbuntuPenguin,
    Your explanation is correct and what I'm trying to find out is an easy way to override that behaviour.
    As an example of what the issue is, let's say an event was entered here, in Toronto,ON, at 3pm, if a customer in Arizona sees the time, he/she will call us immediately to inform us that the event it's supposed to happen at 3pm, and not at 12pm (time that they see with the different timezone).
    As far as I've seen, the "best" way to approach this issue is by using  the transient tag during data transfer and compensate for the time  difference in the client timezone vs the selected "system" timezone  using getters/setters, but that implies storing the wrong date/time and  locking the system into one timezone, and it's just a hack that may  bring undesirable consequences in the future.

  • Fastest way to get data from Multiple lists across multiple site collections

    HI
    I need to get data from multiple lists which spread across 20 site collections and need to show it as list view.
    I have searched on internet about this and got some info like options would be to use search core APIs or BCS . I can't use search because I want real time data. Not sure of any other ways.
    if anybody can provide ideas it would be help.

    Might LINQ be an option for you?  Using
    LINQPad and the
    SharePoint Connector, you should be able to write a query that'll retrieve this data, from which you can tabulate it.  I'm not sure how you'd be able to automate this any further so that it's then imported in as list.
    For something more specific, I used a third party tool called the
    Lightning Tools Lightning Conductor, which is essence a powerful content roll-up tool.  In one of my solutions, I created a calculated column that gave an order / ranking on each item, so that when lists were combined, they'd still have some form of
    order.  The web part is also fairly customisable and has always proven a useful tool.
    Hope that helps.
    Steven Andrews
    SharePoint Business Analyst: LiveNation Entertainment
    Blog: baron72.wordpress.com
    Twitter: Follow @backpackerd00d
    My Wiki Articles:
    CodePlex Corner Series
    Please remember to mark your question as "answered" if this solves (or helps) your problem.

  • Splitting comma seperated column data into multiple rows

    Hi Gurus,
    Please help me for solving below scenario. I have multiple value in single column with comma seperated values and my requirement is load that data into multiple rows.
    Below is the example:
    Source Data:
    Product         Size                                 Stock
    ABC              X,XL,XXL,M,L,S                 1,2,3,4,5,6
    Target Data:
    Product         Size                                 Stock
    ABC              X                                     1
    ABC              XL                                   2
    ABC              XXL                                 3
    ABC              M                                    4
    ABC              L                                      5
    ABC             S                                        6
    Which transformation we need to use for getting this output?
    Thanks in advance !

    Hello,
    Do you need to do this tranformation through OWB mapping only? And can you please tell what type of source you are using? Is it a flat file or a table?
    Thanks

  • How to submit InfoPath form data to multiple SharePoint lists at one time?

    Hi,
    I'm looking for a way to submit certain data in InfoPath form to separate SharePoint lists at the same time. I have a form that has two views with many data in them. I want to keep these data in separate SharePoint list besides keeping them in the XML. I know that you can submit to a form library using SharePoint document library data connection, but I'm not sure if you can use several data connections for submitting data to multiple SharePoint lists. Is it only possible to do using code? If yes, can anyone show a sample. I have never coded in InfoPath, though I used C# a lot in .Net.
    Thank you!Regards,
    R.D.M.

    This is an old thread but I tripped over a codeless method to do this with OOB InfoPath 2010 and SP 2010. 
    Assuming your main InfoPath form is published to a document library with the promoted fields that you want to see.
      Publish your form to a new document library to capture the secondary data fields that you want separated out.
    Using the Publishing Wizard do the following:
    Go to – File then Publish
    Select SharePoint Server “ Publish form to a SharePoint Library”
    Enter location of your SharePoint or InfoPath Forms Services Site: 
    accept the default in this field from the first published event
    Next screen, keep the default or change it, Form Library, Site Content Type or Admin Approved
    Next screen, What do you want to do?
    Create a new form library
    Add new document library name and description
    Next screen, Remove all promoted fields not applicable to the new library and add all of the ones you want to see data for.
    Click Next and Publish
    Come back into the form: If you don’t have buttons added directly to the form to submit or update, add them.
    Create a new Action rule on the button
    Label the rule to keep it straight
    Condition, occurs when button clicked
    Add action, Submit data
    Use data connection to the second library created
    Create a second new Action rule on the same button
    Label the rule to keep it straight
    Condition, occurs when button clicked
    Add action, Submit data
    Use original data connection to the library
    Then you can add another action to close the form or do whatever you need.
    Republish the form to both libraries to set the template for both.
    File – Publish – SharePoint Server
    Select Secondary library from drop down follow the rest of the prompts
    Follow step 5a again, select Primary library from drop down, Add back in all of the promoted fields needed for the primary library and follow the prompts.
    DOCUMENT YOUR FORM WELL FOR MAINTENANCE
    Special considerations, your primary library needs a unique ID to reference in your secondary library.
    Your secondary library will need a unique ID that is not related to the primary if you are going to store multiple records for a single primary library reference. 
    Example: One form, multiple updates.

  • Gantt view - multiple dates in the same row

    Hi,
    I created gantt view showing employees' vacations. Some of them have their holidays split into several dates (periods). How can I show those multiple dates in the same row in the gantt view? I can only show start date and end date of one vacation, but would
    like to enter multiple periods to be shown in the gantt view, in the same row.
    Thanks.

    You can't using the OOTB gantt chart so you would have to look at custom development or 3rd party web parts.
    Such as (blatant plug but it directly answers the OP question) my own companies Planner web part.
    http://www.pentalogic.net/sharepoint-products/planner
    The By Category view puts timelines on the same row so its ideal for things like vacation planning, room booking etc.
    This page shows it in use.
    http://blog.pentalogic.net/2010/08/sharepoint-staff-vacation-planner-absence-wall-chart-dashboard/

Maybe you are looking for

  • OAM 11g Webgate 10g customized SSO logout page

    As stated in the title, I am using OAM 11g and Webgate 10g. I am trying to create a customized SSO logout page but am confused on a few parts. First off, in http://docs.oracle.com/cd/E17904_01/doc.1111/e15478/logout.htm#CHDHFGJC , it states the follo

  • Back-up with Time Capsule using Ethernet?

    I want to backup 1TB of data from an iMac HD using the iMac's ethernet connection. This is not a first connection to the Time Capsule ; I need to recreate the backup after a hard disk failure and replacement. Time Capsule sticks to the wireless netwo

  • I have a vi that will not let me make many edits before it crashes.

    I have been working on a data acquisition program for over a year. Over time it has grown and become more and more complicated. Now the vi will no longer let me make substantial changes. After making edits, when I click, save, LabView crashes. There

  • Acrobat Pro X not converting word docs properly

    When I convert to PDF a word docco with call outs, the text in the callouts is fragmented? has anyone else seen this? (office 2010) I used the print method and the icon on the ribbon both give me the same results. When I use Word to convert to PDF al

  • Is there a "Select all keyframes to the right" command?

    Say in a 16 minute composition, you want to select keyframes from 5 minutes to 16 minutes and shift them earlier in the timeline. Keyframes from 0 to 5 minutes do not change. Can you select multiple keyframes to the right of 5 minutes like this? Perh