Tuomas Antila
Tuomas Antila

Reputation: 35

SQL syntax error after FROM (other_query)

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

Upvotes: 1

Views: 32

Answers (2)

M.Ali
M.Ali

Reputation: 69574

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

Upvotes: 0

juergen d
juergen d

Reputation: 204904

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

Upvotes: 1

Related Questions