How to optimize iterative approach into set based approach

I have an iterative query that I need to optimize with hopefully a set based approach. Every hour it looks at a vehicles gps data and loops over the
data points looking for idle times longer than X minutes. If the vehicle has been idle, but less than X minutes and it starts moving, the idle time is reset, and begins checking for the threshold again when the speed <= 1.
For each vehicle, I only want to know the consecutive idle times greater than X seconds. the thing to note as well, if the idle time doesn't reach the threshold and
the vehicle starts moving, the time is then considered moving time and not idle time.
here is the query - Thanks in advance for any help!
WHILE @iLoop = 1
BEGIN
If( @iCurRow is null) select @iCurRow = 1
Else select @iCurRow = @iCurRow + 1
IF @iCurRow is null Break
select @curTS = TS,
@curIgn = IgnitionOn,
@curSpeed = Speed,
@span = 0
from @temp where ID = @iCurRow
select @nextTS = TS,
@nextSpeed = Speed
from @temp where ID = @iCurRow+1
set @span= isnull(sum(datediff(second,@curTS, @nextTS)),0)
if(@curSpeed <= 1 and @curIgn = 1)
Begin
if(@isIdling = 1)
Begin
set @adjIdle = @adjIdle + @span
End
else if((@cumIdle + @span) >= @idleThreshold)
Begin
set @adjIdle = @adjIdle + @cumIdle + @span
set @cumIdle = 0
set @isIdling = 1
End
else
Begin
set @isIdling = 0
set @cumIdle = @cumIdle + @span
End
End
else if(@curSpeed > 1 and @curIgn = 1)
Begin
set @isIdling = 0
set @adjMove = @adjMove + @cumIdle + @span
set @cumIdle = 0
End
else if @curIgn = 1
Begin
set @isIdling = 0
set @cumIdle = @cumIdle + @span
End
else if @curIgn = 0
Begin
if((@cumIdle) >= @idleThreshold)
Begin
set @adjIdle = @adjIdle + @cumIdle
set @cumIdle = 0
set @isIdling = 0
End
else
Begin
set @adjMove = @adjMove + @cumIdle
set @cumIdle = 0
set @isIdling = 0
End
End
IF @iCurRow+1 = @iMaxRow Break;
END
End

I molded your sample data into INSERT statements (please provide the INSERT
statements yourself next time), and declare variables. I defined the
threshold, and I added a SELECT of what I think is the final output. But it
returns 0 and not 10 as suggested. I have probably not understood the
problem correctly.
Whether this can be done set-based for a single vehicle, I don't know, but I
assume that you are looking at many vehicles at a time. What you definitely
can do is to work with all vehicles at the same time. Number the rows per
vehicle, and the work with all rowno = 1 at once, then rowno = 2 at once
etc.
This is my script as far as I got.
declare @temp as table
   ID int identity,
   TS datetime2,
   IgnitionOn bit,
   Speed decimal(4,1),
   GPIO1 bit,
   GPIO2 bit,
   Location varchar(3),
   Odometer bigint,
   Lat decimal (9,6),
   Lng decimal (9,6)
INSERT @temp (TS, Speed, IgnitionOn)
VALUES
('12:00',   5,   1)   ,
('12:02',   0,   1)   ,
('12:04',   0.5,   1),
('12:06',   0,   1)   ,
('12:08',   0.25,   1),
('12:10',   0,   1)   ,
('12:12',   2,   1)   ,
('12:14',   6,   1)   ,
('12:16',   10,   1) ,
('12:18',   0,   1)    ,
('12:20',   0,   1)   ,
('12:22',   15,   1),
('12:24',   20,   1),
('12:26',   30,   1),
('12:28',   0,   1),
('12:30',   0,   1)
DECLARE @iLoop int = 1,
        @iCurRow int,
        @curTS datetime2,
        @curIgn bit,
        @curSpeed decimal(4, 1),
        @nextTS datetime2 ,
        @nextSpeed decimal(4,1),
        @span      int,
        @isIdling  bit,
        @adjIdle   int,
        @cumIdle       int,
        @idleThreshold int = 10,
        @cumIdling     int,
        @adjMove       int,
        @iMaxRow       int  = (SELECT MAX(ID) FROM @temp)
WHILE @iLoop = 1
BEGIN
          If( @iCurRow is null) select @iCurRow = 1
          Else select @iCurRow = @iCurRow + 1
          IF @iCurRow is null Break
          select @curTS = TS,
                 @curIgn = IgnitionOn,
                 @curSpeed = Speed,
                 @span = 0
               from @temp where  ID = @iCurRow
          select @nextTS = TS,
                  @nextSpeed = Speed
               from @temp where  ID = @iCurRow+1
          set @span= isnull(sum(datediff(second,@curTS, @nextTS)),0)
          if(@curSpeed <= 1 and @curIgn = 1)
          Begin
               if(@isIdling = 1)
               Begin
                    set @adjIdle = @adjIdle + @span
               End
               else if((@cumIdle + @span) >= @idleThreshold)
               Begin
                    set @adjIdle = @adjIdle + @cumIdle + @span
                    set @cumIdle = 0
                    set @isIdling = 1
               End
               else
               Begin
                    set @isIdling = 0
                    set @cumIdle = @cumIdle + @span
               End
          End
          else if(@curSpeed > 1 and @curIgn = 1)
          Begin
               set @isIdling = 0
               set @adjMove = @adjMove + @cumIdle + @span
              set @cumIdle = 0
          End         
          else if @curIgn = 1
          Begin
               set @isIdling = 0
               set @cumIdle = @cumIdle + @span
          End
          else if @curIgn = 0
          Begin
               if((@cumIdle) >= @idleThreshold)
               Begin
                    set @adjIdle = @adjIdle + @cumIdle
                    set @cumIdle = 0
                    set @isIdling = 0
               End
               else
               Begin
                    set @adjMove = @adjMove + @cumIdle
                    set @cumIdle = 0
                    set @isIdling = 0
               End
          End
          IF @iCurRow+1 = @iMaxRow Break;
     END
--End
SELECT @cumIdle
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • SRM SC Migration - How to group SC Items into PO based on a custom made fld

    When migrating Shopping Carts in SRM items are grouped into PO based on Supplier (LIFNR).
    ITEM data in SC has a new, custom made field BE_NR that contains PO numbers from the legacy system.
    Customer wants that PO's are created out of the SC based on the value in BE_NR. They want that items with the same BR_NR are grouped into same PO.
    How can I group all the items with the same BE_NR in one PO?

    Hello,
    You can try the following badis:
    BBP_BS_GROUP_BE - for classic scenario
    BBP_GROUP_LOC_PO - for extended classic scenario
    Regards,
    Ricardo

  • How to read RGB values into Set

    Hi,
    I have been told that to count the total number of unique colors in an image is by reading each pixel RGB values into a set.
    I have checked this and it is true that the set can do this fine if considering only either one channel of the R,G or B (this does not allow me to know the exact number of color exist). However, I am confuse on how to have all three R, G and B values into a set so that the set can consider the whole 3 values of RG and B as a color which can then be differentiated separately.
    I think pixelgrabber allow to getPixel RGB values but I am working with JIU getsample method. Perhaps I missed out other methods in JIU which have the same functionality as in pixelGrabber.
    I am working on an image analysis so I need to figure out this out first.
    I am hoping anyone can help me out with this and I thank you.

    as mentioned, pack the rgb values into an integer.
    instead of a set, you will get better performance and
    memory useage using a sorted, dynamically allocated
    int array. With some minor work, you better this
    structure by using more than one sorted array and a
    cheap rgb mask hashing mechanism. I don't know what
    JIU is, but look at the source of java.awt.Color for
    details on how to pack/unpack rgb values.Hi,
    Thank for your feedback. I have tried to pack the rgb values into an integer. At the moment I just making used of Set (will look into probably ArrayList after I get the rgb values correct). However, I am not sure whether my code is correct (which I doubt) or not. Not sure how the output looks like that. If you could have a look at it and confirm me, I would be very much thanking you.
    the code snippet:
    public void countColour() {
    int r, g, b;
    int[] rgb1DArray = new int[h * w];
    int[] rgb = new int[4];
    Set set = new HashSet();
    int alpha = 255;
    for (int i = 0, cnt = 0; i < w; i++) {
    for (int j = 0; j < h; j++) {
    r = intImg.getSample(0, i, j);
    g = intImg.getSample(1, i, j);
    b = intImg.getSample(2, i, j);
    System.out.println(r+ "," g "," +b); // just checking rgb values
    //rgb[0] = alpha;
    rgb[1] = r;
    rgb[2] = g;
    rgb[3] = b;
    System.out.println(rgb[0]+ "," rgb[1] "," rgb[2] "," +rgb[3]);
    rgb1DArray[cnt] = ((rgb[1])<<16)|
    ((rgb[2]<<8))|(rgb[3]);
    System.out.println("rgb["+cnt+"] :" +rgb1DArray[cnt]);
    output:
    Image file size is 230 x 236
    204,221,203
    0,204,221,203
    rgb[0] :13426123
    204,212,191
    0,204,212,191
    rgb[1] :13423807
    180,166,140
    0,180,166,140
    rgb[2] :11839116
    236,209,166
    0,236,209,166
    rgb[3] :15520166

  • How to optimize query that returns data based on one matching and one missing field joining two tables

    Hi all,
    Here is what I am trying to do. I have 2 tables A and B. Both have a fiscal year and a school ID column. I want to return all data from table B where all school IDs match but fiscal year from A is not in B. I wrote 2 queries below but this took
    2 minutes each to process through 30,000 records in table B. Need to optmize this query.
    1) select 1 from table A inner join table B
    on A.SchoolID=B.SchoolID where A.Year not in (select distinct Year from table B)
    2) select distinct Year from Table A where School ID in (select distinct School ID from table B
    and Year not in (select distinct Year from table B)

    Faraz81,
    query execution time will depend not only on your data volume and structure but also on your system resources.
    You should post your execution plans and DDL to generate data structures so we can take a better look, but one think you could try right away is to store the results of the subquery in a table variable and use it instead.
    You'll also benefit from the creation of:
    1. An index for the B.SchoolID column.
    2. Statistics for the Year column in table B.
    You can also try to change the physical algorithm used to join A to B by using query hints (HASH, MERGE, LOOP) and see how they perform. For example:
    select 1 from table A inner HASH join table B
    on A.SchoolID=B.SchoolID where A.Year not in (select distinct Year from table B)
    As the query optimizer generally chooses the best plan, this might not be a good idea though, but then again, without further information its going to be hard to help you.

  • How to add Phonegap plugins into Thym-based projects?

    Finally got Eclipse working with Phonegap/cordova once I found Thym. However, now I'm not sure how to plugins into the project. Adding them from the CLI as usual does not seem to work.
    Any advice on this? Thanks!

    I installed Thym in my Eclipse Luna.
    Then you can create projects by selecting Cordova platform and plugins when you create the project.
    file> new> other> mobile> Hybrid ...
    but I have not found how to add plugins later.
    Now I installed JBoss Developer Studio and when you click on the Cordova project with right mouse button displays "Install Plugin Cordova".

  • Correlation set based on correlation from raised ADF event payload

    Hi,
    In a BPEL process, how can we include a Correlation set based on correlation from raised ADF event payload ?
    Thanks

    Hi Charles,
    Thanks for the response.
    Actually, my requirement is : I have a BPEL Process which has a pick activity. The OnMessage branch of the Pick activity is mapped to a service which is invoked by a Mediator. This Mediator is Subscribed to a Create Event.
    I am able to run my BPEL and Mediator instances separately but the problem is even though the Mediator is invoking the webservice, after the Create Event is raised, BPEL 's pick activity is not getting the response from the webservice due to which BPEL continues to be in running state.
    This might be a problem with a Correlation Id seting .
    How can i make by BPEL process know about the Mediator instance ? Any idea ?
    Thanks
    Nutan

  • I am locked out of my account because my password includes "[" and my computer is set to spanish. In spanish that key doesn't work. How do I gejt back into my computer?

    i am locked out of my account because my password includes "[" and my computer is set to spanish. In spanish that key doesn't work. How do I gejt back into my computer?

    If the user account is associated with an Apple ID, and you know the Apple ID password, then maybe the Apple ID can be used to reset your user account password.
    Otherwise*, boot into Recovery by holding down the key combination command-R at startup. Release the keys when you see a gray screen with a spinning dial.
    When the OS X Utilities screen appears, select
    Utilities ▹ Terminal
    from the menu bar.
    In the Terminal window, type this:
    res
    Press the tab key. The partial command you typed will automatically be completed to this:
    resetpassword
    Press return. A Reset Password window opens.
    Select your boot volume if not already selected.
    Select your username from the menu labeled Select the user account if not already selected.
    Follow the prompts to reset the password. It's safest to choose a password that includes only the characters a-z, A-Z, and 0-9.
    Select
     ▹ Restart
    from the menu bar.
    You should now be able to log in with the new password, but your Keychain will be reset (empty.) If you've forgotten the Keychain password (which is ordinarily the same as your login password), there's no way to recover it.
    *Note: If you've activated FileVault, this procedure doesn't apply. Follow instead the instructions on this page:
    If you forget the password and FileVault is on

  • HT1911 Someone else set up my itunes account for me and I cant remember the Apple ID, the Password, or the name he put under it all. How do I get back into my iTunes account???

    Someone else set up my iTunes account for me and I can't remember the Apple ID, the Password, or the name he put under it all. How do I get back into my iTunes account???? Or at least a number to call to get back???

    Go to Settings>Store>Apple ID, tap the ID shown, sign out, sign back in using the alternate ID.

  • I recently got IOS 8 and I like it but there is one problem on my camera roll it says i have 600 photos but i went into setting general and about and it says i have 2,743 photos my photos keep on duplicating how do i get this to stop.

    i recently got IOS 8 and I like it but there is one problem on my camera roll it says i have 600 photos but i went into setting general and about and it says i have 2,743 photos my photos keep on duplicating how do i get this to stop. i have a iPhone 5c

    Hi Bpaitin,
    Go to Settings>General>Usage, and under iCloud, click on Manage Storage>click on your device, then under Backup Options, turn Photo Library off and then back on. See if that clears it up.
    If it does not, reset your device (nothing will be lost): Hold down the Home and Power buttons at the same time and continue to hold them down until the Apple appears (up to 30 seconds). Once the Slide to Unlock screen redisplays, see if the issue is resolved.
    Cheers,
    GB

  • The last few times I imported photos, the backup location was set to "documents" with no sub-folders. How do I get them into sub-folders - like year and month?

    the last few times I imported photos, the backup location was set to "documents" with no sub-folders. How do I get them into sub-folders - like year and month?

    Use the Subfolder pulldown to set the subfolders:

  • HT1766 I have had this i-phone almost a year and the last update crashed it.  I back up to i-cloud but this is not a new phone.  How do I get into set-up to restore from i-cloud?

    I have had this i-phone almost a year and the last update crashed it.  I back up to i-cloud but this is not a new phone.  How do I get into set-up to restore from i-cloud?

    From your OLD computer...
    Copy your ENTIRE iTunes FOLDER to an External Drive... and then from the External Drive to your New Computer..
    Full Details Here  >  http://support.apple.com/kb/HT1751
    Also see this migrate iTunes library post by turingtest2

  • How to convert editable pdf into non-editable version for printing option only without setting up passwards?

    I am using IOS system with pdf preview functions. I try to convert editable pdf file into read only for others to print without access to edit the file.
    The only way I can do now is to convert to jpeg for each page and convert back to pdf then combine all pages together. It takes a lot of time in this case.
    Can anyone tell me how to do the conversion without setting up passwards for protection?
    Thank you very much!

    First of all, don't use all CAPS as it means shouting.
    Second, your question is completely off-topic for this forum which discusses Microsoft Office Outlook.
    Third, this is a peer-to-peer forum, don't count on anyone calling you. If you want dedicated support from Microsoft, contact Microsoft Support directly.
    Anyway, you can insert the picture in to OneNote and then have OneNote convert it into text. This usually isn't very accurate for scans though.
    A better solution would be to use a application which is dedicated to OCR. There are various out there. I suggest you try their demo versions to find out which works best with your handwriting.
    Robert Sparnaaij
    [MVP-Outlook]
    Outlook guides and more: HowTo-Outlook.com
    Outlook Quick Tips: MSOutlook.info

  • How to embed chart/grafic into bex report (workbook) based on query result?

    Hi friends,
    Since I have never embedded any Charts/Grafic based on query report, I am wondering if you could share your knowledge?
    Thanks for your help in advance!
    Regards,
    Sally

    Hi Sally,
    You can create chart into workbook based on the query data.
    Execute the query it will show result in excel sheet. In the tool bar of the sheet you find 'Chart wizard' icon . Select the icon, it will ask for the type of the graph. After select the ranges of the data from result. It will display the graph. Then you can save the workbook.
    Graphs can be embedded in different sheets.
    Hope it helps.
    Regards,
    Aditya

  • View offending records in audit viewer for set-based mappings

    i have mappings which is configured to load data from Oracle9i external tables into Fact tables.
    i am using set-based loading with reject limit set to 0. Whenever there's an offending record from the external table, the whole mapping will fail with message 'Fatal error or maximum error exceeded'. This is exactly how i want it.
    now, when i check the mapping process in audit viewer, i expect to see which record caused this process to abort. instead, i only see the same message stated above (which is not very helpful in identify source of the problem, right ?)
    i believe this is due to the mapping being set-based. unfortunately i can't use row-based as i do not want ANY record loaded into the fact table even if there is 1 offending record. In row-based mode, it seems to auto-commit after a certain number of records (bfor any errorneous records are encountered). i have attempted to set the 'commit block size' to something big value (eg. 50,000) but it still seems to commit after say every 2000 records ...
    any suggestions ?
    thanks

    Since you need set based code in order to avoid commits, it is difficult to trap record level errors - the set based procedure will run to the end or encounter an error and all you will get is a generic SQL error code and message. The commit frequency should work - I am not aware of any problems in this area. Can you give more details about this?
    It might also be possible to filter correct records by using a splitter and set it in such a way that correct records get loaded into the production table, while incorrect are 'parked' into a temporary table for review. Another possibility, if you need complex data cleansing prior to loading, would be to use an intermediate staging table and then use the row based mode on it, before transferring the correct records from this staging table to the appropriate production table. This last solution will slow down your process because it introduces an additional step, but might give you the loading flexibility you need.
    Regards:
    Igor

  • IPod w/Cassette Adapter-How to Optimize Sound Quality?

    I have I believe a G2 iPod (15 GB), and I play it in my car using a cassette adapter. I've found that to keep the sound from degrading at above average volumes, I have to make some adjustments. One, I have to set the EQ to 'Bass Reducer'. Two, I have to make sure the volume on the iPod is at about 80%. If I go above that, the sound distorts. The lower you go below that, the more hissing you get w/ the playback. I also turn the 'Sound Check' setting on.
    Any other recommendations on how to optimize the sound quality when playing it through your vehicle sound system? Also, I'm thinking about getting a G5 unit (most likely the 4 GB Nano). Anyone have any feedback on whether I can expect better sound quality, in particular in my vehicle with the setup outlined above, by upgrading to the newer unit?

    Various Methods to Connect to a Car Stereo System, or Listen to Your iPod in the Vehicle
    Best:
    Direct connection via the dock connector or headphone jack of your iPod, to the mini-jack input (or AUX RCA input jacks) of your car stereo. Not many low/moderate-end cars have this feature yet, but it is becoming more popular. Some aftermarket auto stereo units may have this feature.
    There are also some after-market, moderate to fairly expensive direct interfaces, that hook into your existing car stereo to provide a high-quality, direct connection. Most will also power/charge the iPod. Pretty slick, but can be pricey ($80-$300). If money is no object, a clean way to go. Not very portable from car to car – if at all.
    http://logjamelectronics.com/ipodproducts.html
    http://www.myradiostore.us/auxadapters/blitzsafe/blitzsafe-m-link-ipod-interface .html
    http://www.theistore.com/ipod2car.html
    http://www.mp3yourcar.com/
    Better:
    Connect your iPod to a cassette adaptor and play your tunes through your car's cassette player. Some new cars no longer come with a cassette player, so it may not be an option. It will provide even better audio quality if you can run the audio feed out of the dock connector (see the SendStation link below). Can be portable between cars that have a cassette player and also be used in your home cassette system. $5 to $20 for the adaptors, with large variations in quality (even with the same model).
    Good:
    Attach an FM transmitter to your iPod and play the tunes through an unused FM station. Convenient, but wireless FM transmitter signals are susceptible to static and outside interference, and can vary in strength and quality depending on your location. Some noticeable degradation and distortion, depending on the quality of the transmitter, the sensitivity of your ears and the airwave congestion in your area. Highly portable between cars, and may be used in a home system. FM transmitters that need to be plugged into a DC auto jack may not work in a home environment (without some sort of adaptor). You can pay from $15 to more than $80 for some of these.....but for FM quality audio, how much is too much?
    Marginal:
    Attach an external speaker system to the iPod and play it in the car. Workable, but not too good - unless you spring for a $300+ Bose (or similar) system. But why? Only if your vehicle has no Stereo system, perhaps.
    Brave Techno-Geek:
    This site gives some directions on adapting a car stereo by yourself. Risky, but it has been successfully accomplished by a forum member. Fairly inexpensive....unless you screw it up.
    Whichever you choose, power the iPod through your car’s DC power -- either from a power adapter, or as part of the combined audio adaptor. Have a method to secure the iPod to the dash/console/etc. See the reviews for all the various accessories at the iLounge
    You will also get better audio output if the dock connection plug is used, rather than the headphone jack. See Sendstation for a novel adaptor called a PocketDock. Others types are also available via this site.
    I have read positive and negative reviews of each method, and within methods there are great variations in performance of different manufacture's systems – and peoples’ opinions of their performance. Some cassette adaptors/FM transmitters work poorly, some better.
    FWIW: I have the iTrip Mini & the Newer Technology RoadTrip!+ FM transmitters, a Belkin cassette adaptor (used both with & w/out the PocketDock) and two vehicles with the BlitzSafe direct interface. Using the same song in the same car, I found that the FM transmitters worked, but not as good as the cassette adapter via the headphone jack. Using the PocketDock on the cassette adapter resulted in a significant audio quality improvement. As expected, the Blitzsafe direct connect was exceptionally better than everything else: less tinny, a more warmer/richer sound, and close to true CD quality.

Maybe you are looking for

  • Installed new itunes and i cant play my old songs

    installed the new version of itunes and all my songs have an exclamation point next to them and to find where the are located on my computer and i have no idea how to find my songs.

  • Cutom color profiles in lightroom

    i calibrated my screen using colorvision and am trying to print and stay consistant how to i include colorvision as a profile in the print space seetings

  • Uploading data in Background - for CJ27 LSMW recording or BDC

    Hi 1. please suggest the BAPI for creating project with reference to standard project definition/WBS similar to CJ27 or CJ20N with copy project method 2. we tried to upload the data in background for LSMW recording and BDC but geting runtime error wi

  • Newbie flash help

    I'm looking to make a flash banner very similar to the one shown on here [url]http://www.omdesign.co.uk/[/url] I'm really stuck on what techniques i need to use. any advice would be great

  • How can i backup my catalog in PS elements 10

    Backup in photoshop elements 10 continues to baffle me. I go thru the steps as instructed but when my catalog backs up to my external hard drive the files are on in XML format. Where are my pictures? when i attempt to open the file using Photoshop i