Syntax error with LAG function and WITH clause

53 Views Asked by At

I'm currently working with SQL server 2022,my database has a compatibility level of 160, but when I try to execute this statement:

WITH CTE AS
(
    SELECT 
        Id,
        LAG(Id) OVER (ORDER BY Id) AS previous_id,
        Date,
        LAG(Date) OVER (ORDER BY Id) AS previous_date
    FROM 
        dbo.Bellabeat_daily 
)

I get the following error:

Msg 102, Level 15, State 1, Line 6
Incorrect syntax near ')'.

Line 6 correspond to the FROM command.

I checked for misspellings in the columns and the table's name, but everything is correct. I appreciate any advise about what I've missed here.

1

There are 1 best solutions below

3
SelVazi On BEST ANSWER

The correct syntax :

WITH CTE AS(
  SELECT Id,
  LAG(Id) OVER (ORDER BY Id) AS previous_id,
  Date,
  LAG(Date) OVER (ORDER BY Id) AS previous_date
  FROM dbo.Bellabeat_daily 
)
SELECT *
FROM CTE