连接查询中的连接字段

时间:2012-08-15 14:08:07

标签: tsql concatenation for-xml-path

我需要使用来自使用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

这里的问题是我得到了所有reocrds的连接,而不仅仅是在个人ID上分组的reocrds。我已经尝试了各种方法来安排连接,但到目前为止还没有任何工作。

1 个答案:

答案 0 :(得分: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;