Hard Tacos
Hard Tacos

Reputation: 370

SQL Find First Occurrence

I've been at this for about an hour now and am making little to no progress - thought I'd come here for some help/advice.

So, given a sample of my table:

+-----------+-----------------------------+--------------+
| MachineID | DateTime                    | AlertType    |
+-----------+-----------------------------+--------------+
| 56        | 2015-10-05 00:00:23.0000000 | 2000         |
| 42        | 2015-10-05 00:01:26.0000000 | 1006         |
| 50        | 2015-10-05 00:08:33.0000000 | 1018         |
| 56        | 2015-10-05 00:08:48.0000000 | 2003         |
| 56        | 2015-10-05 00:10:15.0000000 | 2000         |
| 67        | 2015-10-05 00:11:59.0000000 | 3001         |
| 60        | 2015-10-05 00:13:02.0000000 | 1006         |
| 67        | 2015-10-05 00:13:08.0000000 | 3000         |
| 56        | 2015-10-05 00:13:09.0000000 | 2003         |
| 67        | 2015-10-05 00:14:50.0000000 | 1018         |
| 67        | 2015-10-05 00:15:00.0000000 | 1018         |
| 47        | 2015-10-05 00:16:55.0000000 | 1006         |
+-----------+-----------------------------+--------------+

How would I get the first occurrence of MachineID w/ an AlertType of 2000 and the last occurrence of the same MachineID w/ and AlertType of 2003.

Here is what I have tried - but it is not outputting what I expect.

SELECT *
FROM [Alerts] a
where 
    DateTime >= '2015-10-05 00:00:00'
    AND  DateTime <= '2015-10-06 00:00:00'
    and not exists(
        select b.MachineID 
        from [Alerts] b
        where   b.AlertType=a.AlertType and
                b.MachineID<a.MachineID
    )
order by a.DateTime ASC

EDIT: The above code doesn't get me what I want because I am not specifically telling it to search for AlertType = 2000 or AlertType = 2003, but even when I try that, I am still unable to gather my desired results.

Here is what I would like my output to display:

+-----------+-----------------------------+--------------+
| MachineID | DateTime                    | AlertType    |
+-----------+-----------------------------+--------------+
| 56        | 2015-10-05 00:00:23.0000000 | 2000         |
| 56        | 2015-10-05 00:13:09.0000000 | 2003         |
+-----------+-----------------------------+--------------+

Any help with this would be greatly appreciated!

Upvotes: 1

Views: 1006

Answers (4)

Dacius
Dacius

Reputation: 94

I think everyone misses that your alert type is NOT a deciding factor, but a supplemental. This should give you what you are looking for. I walked through the whole process. `IF OBJECT_ID('tempdb..#alerts') IS NOT NULL DROP table #alerts

    CREATE TABLE #alerts
    (
    MachineID int,
    dte DATETIME,
    alerttype int
    )
INSERT INTO #alerts VALUES ('56','20151005 00:00:23','2000')
INSERT INTO #alerts VALUES ('42','20151005 00:01:26','1006')
INSERT INTO #alerts VALUES ('50','20151005 00:08:33','1018')
INSERT INTO #alerts VALUES ('56','20151005 00:08:48','2003')
INSERT INTO #alerts VALUES ('56','20151005 00:10:15','2000')
INSERT INTO #alerts VALUES ('67','20151005 00:11:59','3001')
INSERT INTO #alerts VALUES ('60','20151005 00:13:02','1006')
INSERT INTO #alerts VALUES ('67','20151005 00:13:08','3000')
INSERT INTO #alerts VALUES ('56','20151005 00:13:09','2003')
INSERT INTO #alerts VALUES ('67','20151005 00:14:50','1018')
INSERT INTO #alerts VALUES ('67','20151005 00:15:00','1018')
INSERT INTO #alerts VALUES ('47','20151005 00:16:55','1006')
GO
WITH rnk as ( --identifies the order of the records. 
    Select 
        MachineID,
        dte = dte,
        rnk = RANK() OVER (partition BY machineid ORDER BY dte DESC) --ranks the machine ID's based on date (first to Last)
        FROM #alerts
        ),
    agg  as( --Pulls your first  and last record
    SELECT 
        MachineID,
        frst = MIN(rnk), 
        lst = MAX(rnk) 
    FROM rnk 
    GROUP BY MachineID
    )
SELECT
    pop.MachineID,
    pop.dte,
    pop.alerttype

FROM #alerts pop
JOIN rnk r ON pop.MachineID = r.MachineID AND pop.dte = r.dte --the date join allows you to hook into your ranks
JOIN agg ON pop.MachineID = agg.MachineID 
WHERE agg.frst = r.rnk OR agg.lst = r.rnk -- or clause can be replaced by two queries with a union all
ORDER BY 1,2 --viewability... machineID, date`

I personally use cross apply's to preform tasks like this, but CTE's are much more visually friendly for this exercise.

Upvotes: 0

Vinderkay
Vinderkay

Reputation: 23

It looks like your outer section takes all records between 2015-10-05 to 2015-10-06, which includes all the records sorted by date. The inner portion only happens when no records fit the outer date range.

Looks like GSazheniuk has it right, but I am not sure if you just want the 2 records or everything that matches the MachineID and the two alerts?

Upvotes: 1

Tab Alleman
Tab Alleman

Reputation: 31785

Not sure what your attempt has to do with your question, but to answer this:

How would I get the first occurrence of MachineID w/ an AlertType of 2000 and the last occurrence of the same MachineID w/ and AlertType of 2003.

Simple:

SELECT * FROM (
    SELECT TOP 1 * FROM Alerts WHERE AlertType='2000' ORDER BY Datetime ASC
    UNION ALL 
    SELECT TOP 1 * FROM Alerts WHERE AlertType='2003' ORDER BY Datetime DESC
) t

Upvotes: 0

GSazheniuk
GSazheniuk

Reputation: 1384

Not sure, but:

select * from [Table] 
WHERE [DateTime] IN (
            SELECT MIN([DateTime]) as [DateTime] 
            FROM [Table] 
            WHERE AlertType = 2000 
            GROUP BY MachineId 
                UNION ALL 
            SELECT MAX([DateTime]) as [DateTime] 
            FROM [Table] 
            WHERE AlertType = 2003 
            GROUP BY MachineId)
ORDER BY MachineId, AlertType

Upvotes: 2

Related Questions