1

So I'm trying to run this query on my sql server database:

SELECT MAX(timestamp)
FROM (SELECT TOP (20) timestamp
    FROM CPPM_03ChannelCountErrors 
    WHERE '2015-03-10 00:00:00' < timestamp AND timestamp < '2015-03-15 00:00:00' AND skuid = '3252' 
    ORDER BY timestamp)

And I get this error message: "Msg 102, Level 15, State 1, Line 5 Incorrect syntax near ')'."

I have already confirmed that this query by itself works just fine:

SELECT TOP (20) timestamp
FROM CPPM_03ChannelCountErrors
WHERE '2015-03-10 00:00:00' < timestamp AND timestamp < '2015-03-15 00:00:00'
AND skuid = '3252'
ORDER BY timestamp

I'm grateful if someone figures this out. It's driving me insane

2 Answers 2

1
SELECT MAX(timestamp)
FROM 
(
    SELECT TOP (20) timestamp
    FROM CPPM_03ChannelCountErrors 
    WHERE '2015-03-10 00:00:00' < timestamp 
    AND timestamp < '2015-03-15 00:00:00' 
    AND skuid = '3252' 
    ORDER BY timestamp
) tmp

Every subquery needs an alias name. I added it and named it tmp

Sign up to request clarification or add additional context in comments.

Comments

0
SELECT MAX(timestamp)
FROM (SELECT TOP (20) timestamp
    FROM CPPM_03ChannelCountErrors 
    WHERE '2015-03-10 00:00:00' < timestamp 
      AND timestamp < '2015-03-15 00:00:00' AND skuid = '3252' 
    ORDER BY timestamp) t --<-- you need to alias the sub-query here

1 Comment

Why are you using a subquery with a top 20? It looks like you can just use a select max with a single select. Anyway both Juergen and Ali are correct if you want to do it with a sub-query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.