Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server select min value from matching datetime

SELECT Id, Value, Sender, Recipient, MIN(DateTime), TypeOf, VideoId, Likes, Comments
FROM xx.dbo.StreamView
WHERE StreamView.TypeOf = 3 AND StreamView.[DateTime] >= "Some DateTime Value Here"

I am trying to get the latest record directly newer than the given DateTime value.

when executing this query I am receiving the following error:

Msg 207, Level 16, State 1, Line 1
Invalid column name 'Some DateTime Value Here'.

Also, when removing this line AND StreamView.[DateTime] >= "Some DateTime Value Here"

I am getting:

Msg 8120, Level 16, State 1, Line 1 Column 'xx.dbo.StreamView.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Suggestions? Thanks.

Update

WITH
  sequenced_records AS
(
  SELECT
    ROW_NUMBER() OVER (ORDER BY [DateTime] DESC) AS sequence_id,
    *
  FROM
    xx.dbo.StreamView
  WHERE
    StreamView.TypeOf = 3
    AND StreamView.[DateTime] >= "2011-12-29 01:38:21.607"
)
SELECT
  *
FROM
  sequenced_records
WHERE
  sequence_id = 1

returns -> Msg 207, Level 16, State 1, Line 11 Invalid column name '2011-12-29 01:38:21.607'.

Update 2

guys I need to return just a SINGLE record with the minimum datetime in a group of selected items bigger than the given datetime.

like image 278
user1027620 Avatar asked Jan 23 '26 12:01

user1027620


1 Answers

If you are going to use an aggregate function like MIN(), you must group the non-aggregate columns using a GROUP BY clause.

See http://msdn.microsoft.com/en-us/library/ms177673.aspx

You also need to replace the double quotes in "Some DateTime Value Here" with single quotes.

Try this code:

SELECT 
    Id, 
    Value, 
    Sender, 
    Recipient, 
    MIN([DateTime]), 
    TypeOf, 
    VideoId, 
    Likes, 
    Comments
FROM xx.dbo.StreamView

WHERE StreamView.TypeOf = 3 AND StreamView.[DateTime] >= '1/1/2012'

GROUP BY
    Id, 
    Value, 
    Sender, 
    Recipient, 
    TypeOf, 
    VideoId, 
    Likes, 
    Comments

Per the updated question:

DECLARE @Date DATETIME = (
    SELECT MIN( [DateTime] ) FROM xx.dbo.StreamView WHERE TypeOf = 3 
        AND [DateTime] >= '1/1/2012' 
);

SELECT TOP 1 * FROM xx.dbo.StreamView WHERE [DateTime] >= @Date;
like image 186
Tim M. Avatar answered Jan 26 '26 03:01

Tim M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!