如何将两个CTE结合到单个选择语句中

时间:2016-08-16 17:30:58

标签: sql sql-server

您好我正在尝试将两个CTE表达式合并为单个,因为它们都具有几乎相同的连接表。我怎样才能实现这一目标?你的意见很有价值。

SELECT  wf.WorkflowID
            ,COALESCE(STUFF((
            SELECT distinct ''; '', '''' + cOPF.WorkflowLinkID
            FROM Client_1_Workflow mopf`enter code here`
            join Client_1_Workflow_Cell cOPF WITH(NOLOCK) on mopf.WorkflowID = cOPF.WorkflowLinkID
            join Client_1_Workflow iwf WITH(NOLOCK) on cOPF.WorkflowID = wf.WorkflowID
            where iwf.WorkflowID = wf.WorkflowID 
            FOR XML PATH(''''),TYPE).value(''(./text())[1]'',''VARCHAR(MAX)''),1,1,''''),'''') AS WorkflowID
            from Client_1_Workflow   wf WITH(NOLOCK) 


SELECT  wf.WorkflowID
            ,COALESCE(STUFF((
            SELECT distinct ''; '', '''' +mopfn.WorkflowName
            FROM Client_1_Workflow mopfn
            join Client_1_Workflow_Cell cOPF WITH(NOLOCK) on mopfn.WorkflowID = cOPF.WorkflowLinkID
            join Client_1_Workflow iwf WITH(NOLOCK) on cOPF.WorkflowID = wf.WorkflowID
            where iwf.WorkflowID = wf.WorkflowID 
            FOR XML PATH(''''),TYPE).value(''(./text())[1]'',''VARCHAR(MAX)''),1,1,''''),'''') AS WorkflowName
            from Client_1_Workflow wf WITH(NOLOCK) 

3 个答案:

答案 0 :(得分:0)

    SELECT  wf.WorkflowID
                ,COALESCE(STUFF((
                SELECT distinct ''; '', '''' + cOPF.WorkflowLinkID
                FROM Client_1_Workflow mopf`enter code here`
                join Client_1_Workflow_Cell cOPF WITH(NOLOCK) on mopf.WorkflowID = cOPF.WorkflowLinkID
                join Client_1_Workflow iwf WITH(NOLOCK) on cOPF.WorkflowID = wf.WorkflowID
                where iwf.WorkflowID = wf.WorkflowID 
                FOR XML PATH(''''),TYPE).value(''(./text())[1]'',''VARCHAR(MAX)''),1,1,''''),'''') AS WorkflowID
              ,COALESCE(STUFF((
                SELECT distinct ''; '', '''' +mopfn.WorkflowName
                FROM Client_1_Workflow mopfn
                join Client_1_Workflow_Cell cOPF WITH(NOLOCK) on mopfn.WorkflowID = cOPF.WorkflowLinkID
                join Client_1_Workflow iwf WITH(NOLOCK) on cOPF.WorkflowID = wf.WorkflowID
                where iwf.WorkflowID = wf.WorkflowID 
                FOR XML PATH(''''),TYPE).value(''(./text())[1]'',''VARCHAR(MAX)''),1,1,''''),'''') AS WorkflowName
from Client_1_Workflow   wf WITH(NOLOCK) 

这是您的答案的单个查询。在不知道1对多,多对多等的情况下,不可能确定更改连接会如何影响您期望的结果

答案 1 :(得分:0)

如果我正在读你问题中的意图,你想将这些意图附加到另一个上面的表中,然后在两个CTE之间使用UNION ALL或UNION。如果这不是你问题的意图,请忽略。

CTE1
UNION ALL
CTE2;

答案 2 :(得分:-1)

; WITH CTE1 AS
(
BLAH 
)
, CTE2 AS
(
BLAH BLAH
)
SELECT * FROM CTE1 JOIN CTE2 ON CTE1.BLAH = CTE2.BLAH