q1: given a table : ID, Date, S开发者_运维知识库tatus. Write a SQL query which receives @ID @Date and retrieve the status the person with that id on that date or the last status not later than that @date if that date doesn't exist.
I have tried to write queries for above questions. I would appreciate you remarks:
SELECT TOP (1) status from MyTable AS T
WHERE T.Date <= @date && T.id = @id
ORDER BY T.Date
Thanks guys
You need to use AND
instead of &&
, and order by date descending:
SELECT TOP 1 status
from MyTable AS T
WHERE T.Date <= @date
and T.id = @id
ORDER BY T.Date desc
SELECT TOP 1 status from MyTable AS T WHERE T.Date <= @date AND T.id = @id ORDER BY T.Date
精彩评论