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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With