当只有一列具有不同的值时,SQL会在一行上产生多个结果

时间:2016-09-29 09:13:44

标签: sql sql-server

我目前对此有一个类似的查询..

select i.App_Id                       as ApplicationId, 
         Cast(i.ObjectId as NVARCHAR(50)) as ObjectId, 
         1                  as ActivityId, 
         Cast(case 
                when oh.ObjectId is null then 0 
                else 1 
              end as BIT)               as Highlight, 
         iu.UserId                      as UserId
  from   table0 i 
         inner join table1 iu 
                 on i.IdeaID = iu.IdeaID
         left join table2 oh 
                on oh.ObjectId = i.IdeaID 
         left join table3 mIS 
                on i.IdeaID = mIS.IdeaID 
                   AND mIS.EndTime is null 
         inner join table4 mISF 
                 on mISF.StateFluxId = mIS.StateFluxId 
  where  (iu.RelationId = 1 or iu.RelationId = 2) 

正在返回,例如:

2 | 1 | 1 | 1 | 1
2 | 1 | 1 | 1 | 2
2 | 1 | 1 | 1 | 3

我尝试更改它以便在其他列值相同时合并第5列的结果:

2 | 1 | 1 | 1 | 1,2,3

这可能吗?没有设法使用Stuff功能完成它..

谢谢!

2 个答案:

答案 0 :(得分:0)

根据您的代码,我添加了XML PATH()。请根据您的要求进行必要的更改

TFDQuery

答案 1 :(得分:0)

你有没有试过这个,

SELECT DISTINCT i.App_Id AS ApplicationId
    ,Cast(i.ObjectId AS NVARCHAR(50)) AS ObjectId
    ,1 AS ActivityId
    ,Cast(CASE 
            WHEN oh.ObjectId IS NULL
                THEN 0
            ELSE 1
            END AS BIT) AS Highlight
    ,
    --iu.UserId                      as UserId
    (stuff(SELECT ',' + userid FROM table1 WHERE Ideaid = iu.IdeaId FOR XML path(''), 1, 1, '')) AS UserId
FROM table0 i
INNER JOIN table1 iu ON i.IdeaID = iu.IdeaID
LEFT JOIN table2 oh ON oh.ObjectId = i.IdeaID
LEFT JOIN table3 mIS ON i.IdeaID = mIS.IdeaID
    AND mIS.EndTime IS NULL
INNER JOIN table4 mISF ON mISF.StateFluxId = mIS.StateFluxId
WHERE (
        iu.RelationId = 1
        OR iu.RelationId = 2
        )