我正在尝试创建一个CTE,它调用另一个CTE,如下所示。但是我得到了这个错误:
Msg 102,Level 15,State 1,Line 54'''附近的语法不正确。
我真的不知道问题是什么。我检查了一些类似于我和他的其他问题。尝试了那些解决方案,但由于某种原因它不会起作用。
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
);
答案 0 :(得分:2)
您不能拥有with
语句,除非您通过其他语句(通常为select
),但在许多数据库update
和delete
中也是如此。
您的语句有多个CTE,但它没有主要查询部分。错误在分号上,因为它终止了查询。
答案 1 :(得分:1)
你真的需要一个CTE
; 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
或强>
正如Gordon所说,CTE需要后跟SELECT,UPDATE,DELETE语句。
使用您当前的查询,您只需在第二个CTE的末尾选择,它也会返回相同的结果,但这将是一个不必要的步骤。像这样......
;WITH CTE1 (Col1, Col2)
AS
(
-- Some code here
),
CTE2
AS
(
-- Some code here
)
SELECT * FROM CTE2