I have the following SQL statement sample:
SELECT DISTINCT [CommentNdx]
,[CommentsText]
,[DateTimeAdded]
FROM [dbo].[CommentTable]
ORDER BY [dbo].[CommentTable].DateTimeStart DESC
WHERE [CommentsText] = 'Hello World'
I keep getting the error Incorrect syntax near the keyword 'WHERE'. I know the syntax is incorrect but I’m not sure how this should be formatted. Any help is appreciated.
UPDATE:
My mistake, I meant date time start should be datetimeadded. Corrected syntax.
SELECT DISTINCT [TestCommentNdx]
,[TestID]
,[CommentsText]
,[DateTimeAdded]
,[OperatorNdx]
FROM [PTDB].[dbo].[TestsComments]
WHERE [TestID] = 1174411854
ORDER BY [PTDB].[dbo].[TestsComments].[DateTimeAdded] DESC
UPDATE 2:
Thanks much everyone, one last thing, would it make a difference if there were joins in the select statement? I have a really long query with joins and when I try to use DISTINCT, I get ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
The WHERE needs to come before the ORDER BY. Also, you won’t be able to sort by DateTimeStart unless it’s included in the SELECT statement.