0

我需要使用来自使用 INNER JOIN 和 LEFT JOIN 的 T-SQL 查询的连接结果来更新字段。我可以通过更简单的查询使用 STUFF 和 FOR XML PATH 函数来做到这一点,但是我用更复杂的查询来完成相同过程的努力没有成功。

这是一个查询,它为我提供了我需要的结果,ID 字段最终将作为分组,而 Step 字段将是连接值需要位于每个 ID 的一个字段中的那个。

SELECT sc.ID, sc.STEP
FROM Table1 As sc
INNER JOIN Table2 As f
    ON sc.STEP = f.Step AND sc.STEP_TYPE = f.StepType AND   
sc.OldStep = f.OldStep
LEFT JOIN Table3 As l
ON sc.ID = l.ID
WHERE f.Group = l.Group AND sc.CompDate IS NULL

这将使我的结果分解为每个 ID 的多个字段

•ID-----STEP

  • 01 - 101
  • 01 - 102
  • 01 - 103
  • 02 - 107
  • 02 - 113

我需要的是:

•ID-----STEP

  • 01 - 101、102、103
  • 02 - 107, 113

这是我到目前为止所尝试的:

;With OA As 
(   SELECT s.ID, STUFF((
    SELECT ', ' + sc.STEP
    FROM Table1 As sc
    WHERE sc.ID = s.ID
    ORDER BY sc.ID
    FOR XML PATH('')),1,1,'') As Steps
FROM Table1 As s
INNER JOIN Table2 As f
    ON s.STEP = f.Step AND s.STEP_TYPE = f.StepType 
            AND s.OldStep = f.OldStep
LEFT JOIN Table3 As l
    ON s.ID = l.ID
WHERE f.Group = l.Group AND s.CompDate IS NULL
GROUP BY s.ID
)

SELECT * FROM OpenAuditSteps

这里的问题是我得到了所有记录的串联,而不仅仅是按个人 ID 分组的记录。我尝试了各种安排连接的方法,但到目前为止没有任何效果。

4

1 回答 1

0

你就快到了:你的第一个查询已经在工作了。假设结果进入#Table1 然后

SELECT  Distinct
        sc1.ID,
    STUFF (( Select  ',' + sc2.STEP 
    FROM #Table1 AS SC2
    WHERE sc2.ID = sc1.ID
    FOR XML PATH('')),1,1,'') AS STEPS
FROM #Table1 AS SC1
ORDER BY sc1.ID

因此,要使用 WITH 将其组合成一个查询,请尝试以下操作:

    ;WITH IDSteps AS (
SELECT sc.ID, sc.STEP
FROM Table1 As sc
INNER JOIN Table2 As f
    ON sc.STEP = f.Step AND sc.STEP_TYPE = f.StepType AND   
sc.OldStep = f.OldStep
LEFT JOIN Table3 As l
ON sc.ID = l.ID
WHERE f.Group = l.Group AND sc.CompDate IS NULL
)
SELECT  Distinct
        sc1.ID,
    STUFF (( Select  ',' + sc2.STEP 
    FROM IDSteps AS SC2
    WHERE sc2.ID = sc1.ID
    FOR XML PATH('')),1,1,'') AS STEPS
FROM IDSteps AS SC1
ORDER BY sc1.ID;
于 2012-08-15T14:23:50.277 回答