4

I am trying to craft a SQL statement to pull sample values from a DB. The table contains values that pertain to tool changes in a CNC machine. The current statement I have pulls values properly, but only if there is one occurrence of the tool in for a given program. If the tool appears multiple times, the time values correspond from the first load, to the last load. There is only one TIME column, and by finding the first and last occurrence of it, I can determine a tools in/out time.

Basic example:

Raw Data:
Tool_Number    TIME    
100            12:00
100            12:01
100            12:02
100            12:03

Current Query Returns: 
Tool_Number    TIME_IN     TIME_OUT    
100            12:00       12:03

Things get hairy when the tool appears multiple times though, since I can no longer utilize TOP and DISTINCT rules.

Raw Data:
Tool_Number    TIME    
100            12:00
100            12:01
100            12:02
100            12:03
200            12:04
200            12:05
100            12:06
100            12:07

Current Query Returns: 
Tool_Number    TIME_IN     TIME_OUT    
100            12:00       12:07
200            12:04       12:05

Ideal Query Returns:
Tool_Number    TIME_IN     TIME_OUT    
100            12:00       12:03
200            12:04       12:05
100            12:06       12:07

We are doing time analysis, and of course this seriously is messing with the total time values. Current query is:

SELECT * FROM (SELECT DISTINCT SPINDLE_POT FROM TBL_SPINDLE_DATA_M1 
WHERE TIME BETWEEN '4/3/20131:24:13 PM' AND '4/3/2013 3:07:33 PM') AS A 

CROSS APPLY

((SELECT TOP 1 TIME FROM TBL_SPINDLE_DATA_M1 B WHERE B.SPINDLE_POT = A.SPINDLE_POT AND
TIME BETWEEN '4/3/2013 1:24:13 PM' AND '4/3/2013 3:07:33 PM') AS NEWTABLE1

JOIN

(SELECT TOP 1 TIME FROM TBL_SPINDLE_DATA_M1 B WHERE B.SPINDLE_POT = A.SPINDLE_POT 
AND TIME BETWEEN '4/3/2013 1:24:13 PM' AND '4/3/2013 3:07:33 PM' ORDER BY TIME DESC) 
AS NEWTABLE2 ON (0=0))

I am by no means any kind of SQL Query expert! The above query may be horribly wrong, but it does in fact return what I need. Is there anyway to group similar items, but be judicial enough to not group them if their indexes do not touch each other?

4
  • 1
    I am assuming SQL Server due to the use of APPLY but you should make sure that you tag your questions with the appropriate database.
    – Taryn
    Commented Apr 4, 2013 at 18:11
  • Thank you, I am also using SQL 2012 as well. Tag updated. Commented Apr 4, 2013 at 18:13
  • 1
    What exactly is the criterion for values being considered two separate "batches" instead of one? Is it that there must not be a time gap between the two i.e. entries are considered one batch as long as they appear in a continuous manner (minute-wise)? Or is it that there must not be any other tool entry in between (time-wise)? Commented Apr 4, 2013 at 18:19
  • The tools can only be loaded one at a time, so the "batches" must continually(time-wise) be the same tool_number to be grouped together. Or as you put it, There must not be any other tool entry in between(time-wise). Commented Apr 4, 2013 at 18:37

2 Answers 2

10

This is called the "islands problem" and I've seen this as a solution (credit Itzik Ben Gan)

select  tool_number,
        min(time) 'in',
        max(time) 'out',
        count(*)
from    (
    select  tool_number,
            time,
            ROW_NUMBER() OVER (ORDER BY time) - ROW_NUMBER() OVER (PARTITION BY Tool_Number ORDER BY time) AS Grp
    from    #temp
    ) as a
group by grp, tool_number
order by min(time)
1
  • Nice solution, and as a bonus will work on 2005+. I added a LAG/LEAD solution only because I could (2012 questions are pretty rare) and because it seems to lead to a better plan (my solution has one sort compared to three in yours). Commented Apr 4, 2013 at 19:06
7

Here's another approach using LAG/LEAD:

DECLARE @rawdata TABLE(Tool_Number INT, [Time] TIME(0));

INSERT @rawdata VALUES
(100,'12:00'), (100,'12:01'), (100,'12:02'), (100,'12:03'),
(200,'12:04'), (200,'12:05'),
(100,'12:06'), (100,'12:07');

;WITH x AS
(
  SELECT Tool_Number, [Time], 
    s = CASE Tool_number WHEN LAG(Tool_number,1) OVER (ORDER BY [Time]) 
        THEN 0 ELSE 1 END,
    e = CASE Tool_number WHEN LEAD(Tool_number,1) OVER (ORDER BY [Time]) 
        THEN 0 ELSE 1 END
  FROM @rawdata
),
y AS 
(
  SELECT Tool_Number, s, [Time], e = LEAD([Time],1) OVER (ORDER BY [Time]) 
  FROM x WHERE 1 IN (s,e)
)
SELECT Tool_number, TIME_IN = [Time], TIME_OUT = e 
FROM y 
WHERE s = 1
ORDER BY TIME_IN;

Results:

Tool_number  TIME_IN   TIME_OUT
-----------  --------  --------
100          12:00:00  12:03:00
200          12:04:00  12:05:00
100          12:06:00  12:07:00
5
  • This works great, and it is a whole lot faster than the current 'broken' implementation I had cobbled together. Thanks a ton! Commented Apr 4, 2013 at 19:40
  • Nice. Too bad this doesn't work correctly when an island consists of a single row.
    – Andriy M
    Commented Apr 4, 2013 at 20:31
  • Don't know if there can be many ways to fix this, but changing the e expression in y to e = CASE e WHEN 1 THEN [Time] ELSE LEAD([Time],1) OVER (ORDER BY [Time]) END seems to work.
    – Andriy M
    Commented Apr 4, 2013 at 20:41
  • Ah, good catch @AndriyM, I hadn't considered a single-row island! Let me get back to my script and see if there are any other angles. Commented Apr 4, 2013 at 22:02
  • Good to know, though for my dataset this is not an issue since single data rows shouldn't occur. If they do, it's bad data I don't' want it anyway. Commented Apr 8, 2013 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.