gpt4 book ai didi

SQL Server : Combine several SELECT statements with "WITH" part into a UNION

转载 作者:行者123 更新时间:2023-12-02 22:55:17 26 4
gpt4 key购买 nike

我有几个这样的语句(使用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”,就像我上面显示的那样,我会收到以下错误:

Incorrect syntax near the keyword 'UNION'.
Incorrect syntax near the keyword 'with'.
If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon."

我做错了什么?

最佳答案

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 ...

关于SQL Server : Combine several SELECT statements with "WITH" part into a UNION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6685882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com