In mySQL, have a large table of history data and I am looking for an elegant way to be able to select the earliest/latest event types in a single select statement without grouping by Item and Event type and running multiple select statemements if possible as there are quite a few event types to consider. e.g from data like the below:
ID | ITEM | EVENT | DATE |
---|---|---|---|
1 | a | Turn on | 10/09/2023 |
2 | a | Turn on | 11/09/2023 |
3 | a | Update | 11/09/2023 |
4 | a | Restart | 12/09/2023 |
5 | a | Turn on | 10/09/2023 |
6 | a | Turn on | 12/09/2023 |
7 | a | Restart | 10/09/2023 |
8 | a | Turn on | 11/09/2023 |
9 | a | Update | 11/09/2023 |
10 | a | Update | 12/09/2023 |
In order to return the first of each event type per item, I was hoping I could do something clever and neat along the lines of this if possible?
Select ID,
MIN(Date WHERE event = 'Turn On')
MIN(Date WHERE event = 'Update')
MIN(Date WHERE event = 'Restart')
GROUP BY Item
If not the only way I can think of is to group by item and event, select the minumum for each event type and join these all together but was wondering if there is a simpler way?
2
Answers
Just as when pivoting, use a
CASE
expression inside the aggregate.There’s no point in selecting the
ID
column, since the ID is different for each minimum.you need always a
GROUP BY
if you want tp select , multiple items.The solution Barmar provided will only function when sql_mode=only_full_group_by iws disabled
fiddle