Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Posted for Posterity's sake. I just can't find a way to do this without using a cursor. Part of it, I'm sure, is that SQL is not my strong point. If anyone else runs across this post, here's the solution I've used. I'm going to keep plugging away at using a query for it and will post that if I ever figure it out.</p> <pre><code>SET NOCOUNT ON DECLARE @ip VARCHAR(15) SET @ip = '1.1.1.1' DECLARE @dhcplog TABLE(IP VARCHAR(15), HOSTNAME VARCHAR(32), IPDATE DATETIME) DECLARE @results TABLE(IP VARCHAR(15), HOSTNAME VARCHAR(32), STARTDATE DATETIME, ENDDATE DATETIME) INSERT INTO @dhcplog VALUES('1.1.1.1', 'A', '2009-01-01 01:00:00') INSERT INTO @dhcplog VALUES('1.1.1.1', 'A', '2009-01-02 02:00:00') INSERT INTO @dhcplog VALUES('1.1.1.1', 'A', '2009-01-05 03:00:00') INSERT INTO @dhcplog VALUES('1.1.1.1', 'B', '2009-01-07 04:00:00') INSERT INTO @dhcplog VALUES('1.1.1.1', 'B', '2009-01-07 10:00:00') INSERT INTO @dhcplog VALUES('1.1.1.1', 'B', '2009-01-08 05:00:00') INSERT INTO @dhcplog VALUES('1.1.1.1', 'C', '2009-01-09 06:00:00') INSERT INTO @dhcplog VALUES('1.1.1.1', 'A', '2009-01-10 07:00:00') DECLARE @cHOST VARCHAR(32) DECLARE @cEND DATETIME DECLARE @tIP VARCHAR(15) DECLARE @tHOST VARCHAR(32) DECLARE @tIPDATE DATETIME DECLARE IPCursor CURSOR FOR SELECT IP, HOSTNAME, IPDATE FROM @dhcplog WHERE IP = @ip GROUP BY IP, HOSTNAME, IPDATE ORDER BY IPDATE DESC OPEN IPCursor FETCH NEXT FROM IPCursor INTO @tIP, @tHOST, @tIPDATE WHILE @@FETCH_STATUS = 0 BEGIN IF @tHOST = @cHOST BEGIN UPDATE @results SET STARTDATE = @tIPDATE WHERE HOSTNAME = @cHOST AND ENDDATE = @cEND END ELSE BEGIN INSERT INTO @results (IP, HOSTNAME, STARTDATE, ENDDATE) VALUES (@tIP, @tHOST, @tIPDATE, @tIPDATE) SET @cHOST = @tHOST SET @cEND = @tIPDATE END FETCH NEXT FROM IPCursor INTO @tIP, @tHOST, @tIPDATE END CLOSE IPCursor DEALLOCATE IPCursor SELECT * FROM @results SET NOCOUNT OFF </code></pre> <p><strong>Results:</strong></p> <pre><code>IP Hostname StartDate EndDate 1.1.1.1 A 2009-01-10 07:00:00 2009-01-10 07:00:00 1.1.1.1 C 2009-01-09 06:00:00 2009-01-09 06:00:00 1.1.1.1 B 2009-01-07 04:00:00 2009-01-08 05:00:00 1.1.1.1 A 2009-01-01 01:00:00 2009-01-05 03:00:00 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload