Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select rows with max and min date

Tags:

sql

I am trying to get 2 rows from a table at one shot. The one with the minimum datetime (today - 7) of last week and the one which is the latest (today).
My table:

|id  |dataIn |dataOut|date                   |MachineId                            |
-----+-------+-------+-----------------------+-------------------------------------+
|1   |5006   |58     |2011-10-25 09:03:17.000|7B788EE88E-6527-4CB4-AA4D-01B7F4048559  
|2   |1200   |130    |2011-10-26 12:45:43.000|7B788EE88E-6527-4CB4-AA4D-01B7F4048559 
        ...  
|124 |1350   |480    |2011-10-29 13:29:04.000|7B788EE88E-6527-4CB4-AA4D-01B7F4048559  
|125 |8005   |560    |2011-10-31 21:18:35.000|7B788EE88E-6527-4CB4-AA4D-01B7F4048559  

I can select the data from last week with:

SELECT 
dbo.myDatabase.Date AS [date], dbo.myDatabase.dataIn AS [in], 
dbo.myDatabase.dataOut AS [out] 
FROM 
dbo.myDatabase WHERE 
Date >=dateadd(day,datediff(day,0,GetDate())- 7,0) 
AND 
dbo.myDatabase.MachineId = '7B788EE88E-6527-4CB4-AA4D-01B7F4048559' 

but I would only like row 1 AND 125 because those are the rows used for my calculations. So my question is:
How do I select the 2 rows (with MIN and MAX date) from within the results of the previous query?

like image 478
user798612 Avatar asked Nov 01 '11 13:11

user798612


1 Answers

you can use this:

select * from dbo.myDatabase 
where 
    ([Date] = (select max([Date]) from /* your query */ ) or 
    [Date] = (select min([Date]) from /* your query */ ))
    and MachineId = '7B788EE88E-6527-4CB4-AA4D-01B7F4048559' -- or any other id

Edit: since it's entirely possible that two machines have the same date value, the query should be updated to also include a MachineId filter in the where clause. I updated the query to show this.

like image 180
vlad Avatar answered Sep 26 '22 22:09

vlad