Determine Days Since Last Visit

I think I may be overthinking this problem.
What I have is a table that consists of membership data including visit dates. For each visit date, I need to determine the number of days since the last visit.
I'm trying a combination of CTEs and partitions, but it is simply not coalescing in my head.
Following is a sample set of data;
KeyID          MemberID          AdmitDate          Last_Admit_Days
1                 2601                 2014-04-17         
2                 2001                 2014-05-04         
3                 1001                 2014-05-15         
4                 8001                 2014-05-28         
5                 2601                 2014-05-23         
6                 2601                 2014-05-28         
7                 9301                 2014-03-21         
8                 9301                 2014-05-15         
9                 9301                 2014-05-21         
10                8601                2014-05-26         
11                3601                2014-04-13         
12                3601                2014-05-05
I tried putting that in as a code block, but it ended up putting everything on one line.
Anyway, Member # 2601 has three admit dates; 2014-04-17, 2014-05-23 and 2014-05-28. So, the number in the Last_Admit_Days column for those records, should be the DATEDIFF in days between the AdmitDate and the AdmitDate of the immediately prior AdmitDate
for #2601, like this;
KeyID          MemberID          AdmitDate          Last_Admit_Days
1                 2601                 2014-04-17         
0
5                 2601                 2014-05-23         
36
6                 2601                 2014-05-28         
5
I am stumped. Maybe the weekend will refresh me to take a better stab at it, but it's confounding me at the moment and I thought I'd ask here to see if anyone had a quick idea off the top of their heads.
I truly appreciate any assistance.
Thanx!

Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
This is minimal polite behavior on SQL forums. There is no such crap as a“key_id” in RDBMS; that night mare is mix of meta-data and attribute proprieties.
CREATE TABLE Visits
(member_id CHAR(4)NOT NULL,
admission_date DATE NOT NULL,
PRIMARY KEY(member_id,admission_date));
INSERT INTO Visits
VALUES
('2601','2014-04-17'),
('2001','2014-05-04'),
('1001','2014-05-15'),
('8001','2014-05-28'),
('2601','2014-05-23'),
('2601','2014-05-28),
('9301','2014-03-21'),
('9301','2014-05-15'),
('9301','2014-05-21'),
('8601','2014-05-26'),
('3601','2014-04-13'),
('3601','2014-05-05');
SELECT member_id, admission_date,
       DATEDIFF(DAY,
            LAG(admission_date)
            OVER(PARTITION BY member_id
                 ORDER BY admission_date),
             admission_date)
       AS visit_delta
  FROM Visits
  ORDER BY member_id, admission_date;
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • Getting a permission error clicking "Show new posts since last visit".

    If I click "Show new posts since last visit" after I have read a thread, I will get a "You do not have permission to access this page.". This is starting to get a bit annoying. Please look into it.
    Birger

    http://bbs.archlinux.org/viewtopic.php?id=83076

  • MC46 - How is days since last consumption calculated?

    Customer is using MC46 (Analysis of Slow-Moving Items).
    They wish to know where does the days since last consumption come from ?
    Regards.
    Phil.

    hi,
    This depends on the GR which is made on which date...so based on that date till today it will calculate the days...
    Hope it helps..
    Regards
    Priyanka.P

  • 'Mark All Forums Read' from 'View Posts Since Last Visit' pg

    I usually read the forums by the 'View Posts Since Last Visit' method rather than any particular forum. It'd be very nice to have the 'Mark All Forums Read' item on that page as well as the main one to save a trip to that page just for that item. Is this doable?

    jackmetal wrote:
    Another one that I thought would be good (and have actually mentioned before), was to have a 'View Last 24Hrs Posts'...
    Sometimes I'll go in read a post and exit, and of course next time I go in it's all cleaned since then. 
    :shock:
    I'll second that one, too. It's more of a 'disaster recovery' mechanism and wouldn't ordinarily be used, so isn't all that important to me, but it's great when you need it. Most (vBulletin, etc.) boards support that, I believe.

  • Report - Return days since LAST activity

    Hi,
    I need a report that returns "All open SRs with the amount of days since the LAST completed activity of type X" (so we can see when the activity needs to happen again)
    I have managed to create a report that brings back "all open SRs with the amount of days since EVERY completed activity of Type X (so if the activity happened 10 times i get the report returning the SR 10 times).
    I was hoping i could use something like a min function in a pivot table to just return the days since the LAST one but am getting nowhere.
    Any ideas?!?!?!
    Thanks in advance
    Rich

    Hi Guys,
    I'm doing a similar report also.
    I have a analysis based on Activities that returns a list of service requests.
    I have inserted a column with a timediff function to tell me how many days old the activity is. e.g.:
    SR 1, act1, 2 days old
    SR 1, act2, 4 days old
    SR 2, act1, 6 days old
    SR 3, act1, 3 days old
    SR 3, act2, 9 days old
    Using a pivot table i display only the first activity for each SR.
    SR 1, act1, 2 days old
    SR 2, act1, 6 days old
    SR 3, act1, 3 days old
    However i now want to be able to sort the pivot table in descending order of the Day Old column.
    Unfortunately i can't get this to work.
    Any idea's?

  • TM Backup Failed - too many days since last backup

    I moved and it took awhile for me to plugin my TM drive. Finally plugged it in and got an error that says "Backup Failed it has been 89 days since your last backup." There is no option to start a new backup. How do I fix this?

    Hi Jake,
    Try repairing the TM backup using Disk Utility.
    If you back up to a Time Capsule or network disk:
    Open the Time Machine pane of System Preferences, and slide the switch to Off.
    Open Disk Utility, which is in the Utilities folder in the Applications folder.
    Make sure the Time Capsule or network disk is turned on and available.
    Open a Finder window, select your Time Capsule or network disk in the Shared section of the sidebar, and click Connect. If necessary, enter your user name and password.
    On the Time Capsule or network disk, select the disk or volume that contains Time Machine backups. Depending on how your Time Capsule is set up, there may be one or more disks or volumes.
    Locate your backup, and drag it to the Disk Utility sidebar.
    You can identify your backup by looking for your computer’s name in the backup’s filename.
    Select your backup in the Disk Utility sidebar, and then click Repair.
    If the repair is successful, attempt to back up using Time Machine. If the repair is not successful, delete your backup and start a new backup.
    Hope this helps.
    Neville

  • Get # of Days since last modified

    Is there anyway to have a number column that shows the number of days since the item or page was last updated? I was hoping to use a calculated column where [Today]-[Modified] but that doesn't work. A workflow wouldn't work because it would have to keep
    continuously running to keep that column updated.  Any ideas?
    Thanks.   
    Nick Hurst

    We ended up finding some posts online suggesting using Jquery to display this information on the page.  You can put this code in your page layout to display the number of days since the page was last modified or any date field you have associated
    with the page. 
    What we ended up doing was creating a calculated field to just grab a date field (in our case the column 'ReviewDate') and put it in the proper format:
    =TEXT([ReviewDate],"MM/DD/YYYY")
    Then we added a div to the page layout that has this date but is not displayed on the page:
    <div class="review-date-text" style="display:none;">
            <SharePoint:CalculatedField FieldName="ReviewDateDisplay" runat="server" ControlMode="Display"/>
    </div>
    Here's the code, I'm not a developer so there are probably better ways to do this but I was able to piece this together from a couple different posts:
    //The following gets the number of days since article was reviewed and writes the value into a right col div
    //Gets Todays date and format it as date
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth();
    var yyyy = today.getFullYear();
    if(dd<10) {
    dd='0'+dd
    if(mm<10) {
    mm='0'+mm
    var todaysDate = new Date(yyyy,mm,dd);
    //Finds the text value of the review date
    //The review date is in the review-date-text div
    var reviewdatetext = jQuery(".review-date-text").text();
    var reviewdatetext = jQuery.trim(reviewdatetext);
    //Parses the review date and formats as a new date
    var dateParts = reviewdatetext.split('/')
    var reviewyear = dateParts[2];
    var reviewday = dateParts[1];
    var reviewmonth = dateParts[0]-1;//January is 0!
    var reviewDate = new Date(reviewyear,reviewmonth,reviewday);
    //Finds the number of days difference between today and review date
    oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
    var diffDays = Math.round(Math.abs((todaysDate.getTime() - reviewDate.getTime())/(oneDay)));
    //Appends the number of days to the review-date div in the right column
    jQuery("<div class='Custom-Date-Review'>"+diffDays+" days ago</div>").appendTo("#review-date");
    Works great for us, hope that helps someone else. 
    Nick Hurst

  • Problems getting days since last used for licensed software

    Using SCCM 2007 SP2 R3
    We've been required to start removing certain licensed software after 60 days of non-use.  Tried the canned reports, but needed to do a customized one to get all the needed info:
    SELECT DISTINCT SYS.Netbios_Name0 AS 'NAME', CSYS.Manufacturer0 AS 'MFG', CSYS.Model0 AS 'MODEL'
    , PCB.SerialNumber0 AS 'SN#', SCUM.TopConsoleUser0 AS 'TOP USER'
    , RUA2.LastUserName0 AS 'LAST APP USER', OSYS.Caption0 AS 'OS', SMSIS.SMS_Installed_Sites0 AS 'SITE'
    , SYS.Resource_Domain_OR_Workgr0 AS 'DOMAIN', RUA2.ExplorerFileName0 AS 'FILE', RUA2.FileDescription0 AS 'PRODUCT'
    ,RUA2.ProductVersion0 AS 'METERED VERSION', SWF.FileVersion AS 'FILE VERSION'
    , CASE WHEN MIN(DateDiff(day, RUA2.LastUsedTime0, GetDate())) IS NULL THEN CAST('NOT USED'AS VARCHAR)
    ELSE CAST (MIN(DateDiff(day, RUA2.LastUsedTime0, GetDate())) AS VARCHAR)
    END AS 'VISIO LAST USED (> 60 DAYS)'
    FROM dbo.v_R_System SYS
    JOIN dbo.v_GS_SoftwareFile SWF ON SYS.ResourceID = SWF.ResourceID
    JOIN dbo.v_Add_Remove_Programs ARP ON SYS.ResourceID = ARP.ResourceID
    JOIN dbo.v_GS_COMPUTER_SYSTEM CSYS ON SYS.ResourceID = CSYS.ResourceID
    JOIN dbo.v_GS_PC_BIOS PCB ON SYS.ResourceID = PCB.ResourceID
    JOIN dbo.v_GS_OPERATING_SYSTEM OSYS ON SYS.ResourceID = OSYS.ResourceID
    JOIN dbo.v_RA_System_SMSInstalledSites SMSIS ON SYS.ResourceID = SMSIS.ResourceID
    JOIN dbo.v_GS_SYSTEM_CONSOLE_USAGE_MAXGROUP SCUM ON SYS.ResourceID = SCUM.ResourceID
    LEFT OUTER JOIN dbo.v_GS_CCM_RECENTLY_USED_APPS RUA2 ON SYS.ResourceID
    = (SELECT RUA2.ResourceID WHERE RUA2.ExplorerFileName0 = 'acrobat.exe')
    WHERE (SWF.FileName = 'acrobat.exe'
    AND SWF.FilePath LIKE 'c:\program%')
    AND SYS.Operating_System_Name_and0 LIKE '%workstation%'
    AND SYS.Client0 = '1'
    AND SYS.Obsolete0 = '0'
    AND ARP.DisplayName0 LIKE '%adobe %acrobat %'
    AND ARP.DisplayName0 NOT LIKE '%mui%'
    AND ARP.DisplayName0 NOT LIKE '%viewer%'
    AND ARP.DisplayName0 NOT LIKE '%pack%'
    AND ARP.DisplayName0 NOT LIKE '%update%'
    AND ARP.DisplayName0 NOT LIKE '%web%'
    AND ARP.DisplayName0 NOT LIKE '%modeler%'
    AND ARP.DisplayName0 NOT LIKE '%hotfix%'
    AND ARP.DisplayName0 NOT LIKE '%browser%'
    AND ARP.DisplayName0 NOT LIKE '%workgroup%'
    AND ARP.DisplayName0 NOT LIKE '%english%'
    AND ARP.DisplayName0 NOT LIKE '%extended%'
    AND ARP.DisplayName0 NOT LIKE '%cpsid%'
    GROUP BY SYS.Netbios_Name0, CSYS.Manufacturer0, CSYS.Model0, PCB.SerialNumber0, SYS.User_Name0, OSYS.Caption0, SMSIS.SMS_Installed_Sites0
    , SYS.Resource_Domain_OR_Workgr0, RUA2.ExplorerFileName0, RUA2.ProductName0, RUA2.FileDescription0
    , RUA2.ProductVersion0, RUA2.LastUserName0, SWF.FileVersion, SCUM.TopConsoleUser0
    HAVING MIN(DateDiff(day, RUA2.LastUsedTime0, GetDate())) > '60'
    OR MIN(DateDiff(day, RUA2.LastUsedTime0, GetDate())) IS NULL
    ORDER BY 'DOMAIN', 'SITE', 'NAME'
    It produces output similar to the below:
    NAME
    MFG
    MODEL
    SN#
    TOP USER
    LAST APP USER
    OS
    SITE
    DOMAIN
    FILE
    PRODUCT
    METERED VERSION
    FILE VERSION
    ACROBAT LAST USED (> 60 DAYS)
    ECH-WS73030
    BIOSTAR Group
    P43D3
    None
    vha19\vhadengethoh
    NULL
    Microsoft Windows 7 Enterprise
    ECH
    VHA19
    NULL
    NULL
    NULL
    11.0.06.70
    NOT USED
    ECH-WS60512
    Dell Inc.
    OptiPlex 990
    FZVCHS1
    vha19\vhaechconnel
    VHA19\VHAECHSchneA
    Microsoft Windows 7 Enterprise
    ECH
    VHA19
    Acrobat.exe
    Adobe Acrobat
    11.0.03.37
    11.0.06.70
    87
    Running into two problems:
      1.  Despite the product actually being used on some computers, Recently Used Apps (RUA) View shows no usage (none in other SW Metering views, either) and not sure what the issue is--SW and HW inventory are both working perfectly fine, as
    are the metering processes on the site server.  Gives me a lot of false positives for not being used.
      2.  Have found some cases in which a previous version was installed, and used, then later upgraded, but not used--however, seems no way to filter out just usage for the CURRENT version.  Have looked at comparing the SW File Version and the
    RUA.File Version, but they are often not identical, particularly if the product was patched.
    Is there a better way to determine usage, or a better custom report to use?
    Thanks.

    I'm cleaning up old post, did you figure this out, if so how?
    http://www.enhansoft.com/

  • Time since last update

    Hi
    I regularly update my website sometimes once a day sometimes several times. I would to place a script or something on the page that places a "mins/hours/days" since last update. Similar to post columns on forums. I have looked through Dreamweaver exchange but cannot find anything (or have i missed it)
    thanks

    Most likely you will require PHP and such to do that. JavaScript as such cannot list files and their properties etc.. File system access goes against its security model.
    Mylenium

  • I am using iphone 3gs since last 4 days. Till yesterday night it was working fine and i have connected this phone for charging . Morning there was apple logo in the screen and every 1mte (approx) it is blinking. I could not restart the phone.Plz help

    I am using iphone 3gs since last 4 days. Till yesterday night it was working fine and i have connected this phone for charging . Morning there was apple logo in the screen and every 1mte (approx) it is blinking. I could not restart the phone.Plz help . I have tried to reset even by pressing sleep and home button but it could not help. Please suggest. Still i have connected for charging .

    Sounds like you have corrupt backup data, if this occurs from one phone to another. Try restoring the phone as a new device, without a backup. Try using for a day before installing any other apps, etc. See if that improves the battery life. Then try syncing back applications a couple at a time. Something seems to be locking in the processor which is draining the battery.
    Do you live in an area where there are Apple Stores? If so, try making an appointment with the Genius Bar to have the device checked out.

  • My iphone6 screen is off since last few days i have tried all the options like pressing the home and sleep button together but still its not switching it on before it was getting hanged quite often it had full battery charged but still it is off

    my iphone6 screen is off since last few days i have tried all the options like pressing the home and sleep button together but still its not switching it on before it was getting hanged quite often it had full battery charged but still it is off can anyone please help ......

    hi i m currently in pakistan and there is no apple store here . i will b back to australia after 2 weeks i was wondering if thei can b any fix as i have all my contacts and everything else in my mobile

  • HT1871 Hi. my iphone 4 is getting heated and battery is getting lower & lower. since last 4 days i am facing this problem. please help me

    Dear Team,
    Since last 4 days after i have replaced display of my iphone 4, my handset is getting heated & battery is getting discharged in no time. i mean in morning i am doing full charge & before noon its getting low.
    please help
    Ravi Vyas

    Will it get rectified and restored...if so after how long. What could be the reason for such outage kindly share,  as I am facing real problem because of this...

  • HT5137 Unable to download more than 8 per cent of telegraph app for last 4 days since they upgraded it can you suggest anything to make it work

    Have been unable to download telegraph subscription for last 4  days since they up graded the ap. can you tell me how to restore it please?

    You're the second person in two days having trouble with the Telegraph update. Step one is a reset. Press and hold both the home and power buttons for 10-15 seconds till the Apple logo appears. Release both buttons. Wait 15-20 seconds till your iPad starts on it's own.

  • Import running slow since last days.

    I have a issue where Oracle 9i database import is running very slow since last couple of days. The process used to be completed in 5 hours every day. But since last two days it is taking 10 to 15 hours to complete. I have checked the data-file size, and export dump-file sizes are consistent with what it used to be. There are no any significant changes in the database size no errors reported in the import and alert log files. Please help me Identify and resolve the real cause of this performance degrade.
    Thanks,
    Farhan
    Edited by: 884977 on Dec 2, 2012 11:25 AM

    --Exact OS version
    SunOS dbw01 5.10 Generic_141444-09 sun4v sparc SUNW,SPARC-Enterprise-T2000
    --Oracle database version
    Oracle9i Release 9.2.0.6.0 - 64bit Production
    PL/SQL Release 9.2.0.6.0 - Production
    CORE 9.2.0.6.0 Production
    TNS for Solaris: Version 9.2.0.6.0 - Production
    NLSRTL Version 9.2.0.6.0 - Production
    --Lines from import logfile
    Connected to: Oracle9i Release 9.2.0.6.0 - 64bit Production
    JServer Release 9.2.0.6.0 - Production
    Export file created by EXPORT:V09.02.00 via direct path
    import done in US7ASCII character set and AL16UTF16 NCHAR character set
    import server uses WE8ISO8859P1 character set (possible charset conversion)
    export client uses AL32UTF8 character set (possible charset conversion)
    . importing CFD_USER's objects into CFD_USER
    . . importing table "CFD_ACCOUNT_POLICY" 613 rows imported
    . . importing table "CFD_ACTIVE_EMPLOYEE_COUNT" 0 rows imported
    . . importing table "CFD_ADDRESS" 1435608 rows imported
    . . importing table "CFD_APPEAL" 1688 rows imported
    . . importing table "CFD_APPEALS_DOCUMENTS_LNK" 5155 rows imported
    . . importing table "CFD_APPEAL_NOTES_LNK" 2564 rows imported
    . . importing table "CFD_CALC_METHOD_CHANGE_HELPER" 38323 rows imported
    . . importing table "CFD_CODE" 379 rows imported
    . . importing table "CFD_CONSTRAINT_CONTEXT" 2823 rows imported
    . . importing table "CFD_CONSTRAINT_CRITERIA" 34070 rows imported
    . . importing table "CFD_CONTACT_INFORMATION_MV" 32018 rows imported
    --Command used
    imp CFDa_user/xxxxxxxx parfile=/export/home/oracle/shells/cfdtables.par file=/oradata/dump/cfdtables.dmp log=/oradata/dump/CFD_tablesimp.log ignore=y recordlength=65535 trace=y
    Thanks,

  • Please i need you to send me my verification email so that i can download apps..this is sooo annoying i've been waiting for email since last day..what happened APPLE???please fix this thank you.

    I NEED MY VERIFICATION EMAIL SO I CAN DOWNLOAD APPS I'VE BEEN WAITING FOR EMAIL SINCE LAST DAY..PLEASE FIX THIS HELP ME..THANK YOU

    This is a user-to-user forum hosted by Apple. You are only talking to other users here not Apple.
    If you you wish to talk to Apple Support use http://www.apple.com/contact/

Maybe you are looking for

  • Constant Selection in BEx Query Designer on BI7

    Hi guys According to this blog <a href="/people/prakash.darji/blog/2006/09/19/the-hidden-secret-of-constant-selection Selection</a>, we can create constant selection on both Characteristics and Key figures. I understand how to do it with restricted k

  • USER_EXIT used in Form6i

    We are using forms 6i as the front end with oracle10.2.0 as the back end.We have forms developed in Oracle Forms 6i which use user_exit function supported by earlier versions of Oracle.I would like to know that if we want to continue using Oracle For

  • How to deploy Mobile Time & Travel to PDA

    Is it possible to deploy SAP Mobile Time & Travel to a PDA device? On the MarketPlace, there are some documentation about Mobile Time & Travel for Laptop but I couldn't find anything about PDA.  If it is possible, would you please guide me through th

  • How can I generate C code from vi?

    I have a complicated VI with several subVIs and I've to create a c code to increase the program speed and transfer rate of data. This VI is working with a can card to transfer data in a Software in the Loop application. In future I've to implement th

  • Dell Latitude XT (Radeon X1250) issue

    Hello I recently bought used Latitude XT and now I know I should have rather bought XT2 :-\ After recent upgrade (kernel switched to 3.5.x) I get tons of visual artifacts from the opensource driver - mainly garbage fonts but also pictures are display