Question

I am trying to create a CTE which calls another CTE as follows. But I get this error:

Msg 102, Level 15, State 1, Line 54 Incorrect syntax near ';'.

I cannot really see what the problem is. I checked out a bunch of other questions similar to mine & tried out the solution from those, but it won't work for some reason.

With SEASONALITY_AVG_REVENUE
(
    YearKey
    ,Aggregation_Key
    ,Yearly_Avg_Revenue
)   
as
(
    SELECT
        ts.YearKey,
        agg.Aggregation_Key,
        Yearly_Avg_Revenue = AVG(agg.Revenue)

    FROM 
        seasonality_custom.TIME_SERIES_INDEX ts
        INNER JOIN seasonality_custom.SEASONALITY_AGG_TIME_SERIES agg
        ON ts.TIME_SERIES_INDEX = agg.TIME_SERIES_INDEX
    GROUP BY
        ts.YearKey,
        agg.Aggregation_Key  
)
, SEASONALITY_ALL_RECS
(
    YearKey
    ,Aggregation_Key
    ,Revenue
    ,Yearly_Avg_Revenue
)   
as
(
    SELECT
        ts.YearKey,
        agg.Aggregation_Key,
        agg.Revenue,
        Yearly_Avg_Revenue = savg.Yearly_Avg_Revenue
    FROM 
        seasonality_custom.TIME_SERIES_INDEX ts
        INNER JOIN seasonality_custom.SEASONALITY_AGG_TIME_SERIES agg
        ON ts.TIME_SERIES_INDEX = agg.TIME_SERIES_INDEX
        INNER JOIN SEASONALITY_AVG_REVENUE savg
        ON ts.YearKey = savg.YearKey and agg.Aggregation_Key = savg.Aggregation_Key
);
Était-ce utile?

La solution

You cannot have a with statement unless you follow it by some other statement, typically select but in many databases update and delete as well.

Your statement has multiple CTEs, but it doesn't have the main query part. The error is on the semi-colon because that terminates the query.

Autres conseils

You really need one CTE here

; With SEASONALITY_AVG_REVENUE(YearKey, Aggregation_Key, Yearly_Avg_Revenue)   
AS
 (
SELECT  ts.YearKey,
        agg.Aggregation_Key,
        Yearly_Avg_Revenue = AVG(agg.Revenue)

FROM seasonality_custom.TIME_SERIES_INDEX ts INNER JOIN 
seasonality_custom.SEASONALITY_AGG_TIME_SERIES agg
ON ts.TIME_SERIES_INDEX = agg.TIME_SERIES_INDEX
GROUP BY ts.YearKey, agg.Aggregation_Key  
  )

SELECT ts.YearKey,
        agg.Aggregation_Key,
        agg.Revenue,
        Yearly_Avg_Revenue = savg.Yearly_Avg_Revenue
FROM seasonality_custom.TIME_SERIES_INDEX ts
INNER JOIN  seasonality_custom.SEASONALITY_AGG_TIME_SERIES agg
ON ts.TIME_SERIES_INDEX = agg.TIME_SERIES_INDEX
INNER JOIN SEASONALITY_AVG_REVENUE savg
ON ts.YearKey = savg.YearKey and  agg.Aggregation_Key = savg.Aggregation_Key

Or

As Gordon has mentioned CTE needs to be followed by a SELECT, UPDATE, DELETE statement.

With your current query you can simply select at the end from your second CTE and it will also return the same results but it will be an unnecessary step. Something like this..

;WITH CTE1 (Col1, Col2)
AS 
  (
    -- Some code here
  ),
CTE2
AS 
  (
     -- Some code here
  )
SELECT * FROM CTE2
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top