SQL Server:将几个带有“WITH”部分的SELECT语句组合到一个UNION中

时间:2011-07-13 21:25:11

标签: sql sql-server select union

我有几个这样的语句(使用WITH语句):

WITH valDiff AS (SELECT <ComplexClause1> AS v1 FROM [MyTable] WHERE <OtherClause1>) SELECT SUM(CASE WHEN v1 < @MaxVal THEN v1 ELSE @MaxVal END) FROM valDiff

UNION

WITH valDiff AS (SELECT <ComplexClauseN> AS v1 FROM [MyTable] WHERE <OtherClauseN>) SELECT SUM(CASE WHEN v1 < @MaxVal THEN v1 ELSE @MaxVal END) FROM valDiff

我需要将它们合并到一个联合中,以便“一举”返回结果。这些语句本身可以正常工作,但如果我在它们之间添加单词“UNION”,就像我上面所示,我得到以下错误:

  

关键字'UNION'附近的语法不正确。
关键字'with'附近的语法不正确。
如果此语句是公用表表达式,xmlnamespaces子句或更改跟踪上下文子句,则必须以分号结束前一个语句。“

我做错了什么?

2 个答案:

答案 0 :(得分:8)

WITH将跨越UNION中的所有子句

;WITH valDiff AS 
(
whatever
) 
SELECT ... FROM valDiff ...
UNION ALL
SELECT ... FROM valDiff ...

每个子句中都有不同的CTE(如本例所示):

;WITH CTE1 AS 
(
whatever
) , CTE2 AS
(
something
)
SELECT ... FROM CTE1 ...
UNION ALL
SELECT ... FROM CTE2 ...

答案 1 :(得分:1)

稍微重新排列语法,以便所有CTE排在第一位:

WITH valDiff1 AS (SELECT <ComplexClause1> AS v1 FROM [MyTable] WHERE <OtherClause1>), 
     valDiff2 AS (SELECT <ComplexClauseN> AS v1 FROM [MyTable] WHERE <OtherClauseN>)
SELECT SUM(CASE WHEN v1 < @MaxVal THEN v1 ELSE @MaxVal END) FROM valDiff1
UNION ALL
SELECT SUM(CASE WHEN v1 < @MaxVal THEN v1 ELSE @MaxVal END) FROM valDiff2