【发布时间】:2021-09-11 03:15:53
【问题描述】:
我正在使用for xml path 来汇总值:
select max(x.Ids), max(x.Number), (select country,city for json path) as [Json]
from t
outer apply (
select Stuff((select ',' + Convert(varchar(10),t2.Id)
from t t2
where t2.city=t.city and t2.country=t.country
for xml path(''),type).value('(./text())[1]','varchar(10)'),1,1,'') as Ids,
Stuff((select ',' + Convert(varchar(10),t2.Number)
from t t2
where t2.city=t.city and t2.country=t.country
for xml path(''),type).value('(./text())[1]','varchar(10)'),1,1,'') as Numbers
)x
outer apply 中的选择案例/查询是相同的。我想知道是否可以重用这个查询?我尝试在 outer apply 内创建一个 CTE,但这似乎不被 SQL Server 接受:
select max(x.Ids), max(x.Number), (select country,city for json path) as [Json]
from t
outer apply (
with Test_CTE( Id, Number) AS (
SELECT ID, Number FROM t t2
where t2.city=t.city and t2.country=t.country
)
select Stuff((select ',' + Convert(varchar(10),t2.Id)
from Test_CTE t2
for xml path(''),type).value('(./text())[1]','varchar(10)'),1,1,'') as Ids,
Stuff((select ',' + Convert(varchar(10),t2.Number)
from Test_CTE t2
for xml path(''),type).value('(./text())[1]','varchar(10)'),1,1,'') as Numbers
)x
上述尝试给出以下错误:
关键字“with”附近的语法不正确。
【问题讨论】:
-
您不能以这种方式使用公用表表达式。您使用的是什么版本的 SQL Server?
-
Unlick 子查询,CTE 必须在语句的开头定义。 WITH CTE AS ({select statement here}) 应该出现在实际的 select 语句之前。
-
CTE 是在你开始的 start 定义的,而不是中间。
标签: sql-server with-statement for-xml-path