SQL查询基于id在一个字段中选择多个行

时间:2016-12-22 09:48:02

标签: sql sql-server tsql sql-server-2012

我有这个问题:

{{1}}

这几乎正常工作,唯一的问题是我在一个字段中连接了所有记录,但我想获取特定于该ID的所有字段,请查看屏幕截图documentation

正如您在第一个结果中看到的那样,所有值都被连接起来并且忽略了LiveTrainingId,但我想要获得的只是特定于LiveTrainingId连接的三个值。

3 个答案:

答案 0 :(得分:1)

这些联接是不对的。子查询中的别名lt将覆盖外部FROM子句中具有相同名称的别名,这是您真正想要匹配的内容。重命名别名以使它们是唯一的 - 请注意 2 - 应该有效:

SELECT Id,
SUBSTRING(
(SELECT ',' + lts2.Selection
FROM LiveTrainingSelections lts2 
INNER JOIN LiveTraining lt2 ON lt2.Id = lts2.LiveTrainingId
WHERE lts2.SelectionType = 'Session Format' and lts2.LiveTrainingId = lt.Id
FOR XML PATH('')),2,200000) AS SelectionDetails
 FROM LiveTraining lt
JOIN LiveTrainingSelections lts 
ON lt.Id = lts.LiveTrainingId

但是根据您的查询,我猜测连接实际上是多余的,您只想从外部查询中的LiveTraining和内部查询中的LiveTrainingSelections中选择:

SELECT Id,
SUBSTRING(
(SELECT ',' + lts.Selection
FROM LiveTrainingSelections lts 
WHERE lts.SelectionType = 'Session Format' and lts.LiveTrainingId = lt.Id
FOR XML PATH('')),2,200000) AS SelectionDetails
FROM LiveTraining lt    

答案 1 :(得分:0)

我认为我们可以使用STUFF完成,请尝试,如果它能为您提供所需的输出:

SELECT ltd.Id,
STUFF((SELECT ',' + lta.Selection FROM FROM LiveTrainingSelections lta
        WHERE lt.Id = lta.LiveTrainingId 
        AND lta.SelectionType = 'Session Format' 
                                 FOR XML PATH('')),1,1,'') AS SelectionDetails,            
FROM LiveTraining lt
INNER JOIN LiveTrainingSelections lts ON lt.Id = lts.LiveTrainingId
GROUP BY ltd.Id

答案 2 :(得分:0)

请尝试以下sql:

SELECT  It.Id, STUFF((SELECT  ',' + lts.Selection
            FROM LiveTrainingSelections lts 
            WHERE  lts.LiveTrainingId = lt.Id
            ORDER BY lts.LiveTrainingId
        FOR XML PATH('')), 1, 1, '') AS listStr
FROM LiveTraining lt
WHERE exists(
SELECT 1 FROM LiveTrainingSelections lts2
WHERE lt.Id = lts2.LiveTrainingId
and lts2.SelectionType = 'Session Format'
)
GROUP BY lt.Id