4

I tried a lot but can't find what is wrong with this query, It gave me this error:

Incorrect syntax near ')'.

string query = "SELECT SUM(See) AS [All]
 , (
       SELECT TOP 1 See
       FROM StateSite
       WHERE StatDate = @StatDate
   ) AS [Now]
 , (
       SELECT TOP 1 See
       FROM StateSite
       WHERE StatDate = @Yesterday
   ) AS [Last]
 , (
       SELECT SUM(See)
       FROM (
           SELECT TOP 7 *
           FROM StateSite
           ORDER BY id DESC
       )
   ) AS [week]
FROM StateSite";

also that works properly with access database but not by sql server.

DineshDB
  • 5,998
  • 7
  • 33
  • 49
Bahareh Feizi
  • 55
  • 1
  • 1
  • 3

3 Answers3

6

Your issue is you are trying to select from a subquery without assigning an alias to the result set.

All you have to do is change your query from this

string query = "select sum(See) as[All] ,(select top 1 See from StateSite
where StatDate=@StatDate)as[Now], (select top 1 See from StateSite where
StatDate=@Yesterday)as[Last],(select sum(See)  from  (select top 7 * from
StateSite order by ID desc))as[week] From StateSite";

To this

string query = "select sum(See) as[All] ,(select top 1 See from StateSite
where StatDate=@StatDate)as[Now], (select top 1 See from StateSite where
StatDate=@Yesterday)as[Last],(select sum(See)  from  (select top 7 * from
StateSite order by ID desc) as [subQuery])as[week] From StateSite";
Tony
  • 9,672
  • 3
  • 47
  • 75
GeoffWilson
  • 433
  • 7
  • 21
3
SELECT
    [All] = SUM(See),
    [Now] = MAX(CASE WHEN StatDate = @StatDate THEN See END),
    [Last] = MAX(CASE WHEN StatDate = @Yesterday THEN See END),
    [week] = SUM(CASE WHEN RowNum < 8 THEN See END)
FROM (
    SELECT *, RowNum = ROW_NUMBER() OVER (ORDER BY id DESC)
    FROM StateSite
) t
Devart
  • 119,203
  • 23
  • 166
  • 186
2

You can try to directly run your query to database and check if syntax is correct. There can be multiple () where your query might be failing. For example in my case the argument passed for IN clause was empty creating my query something like select * from tableName where id in () and hence was getting error.