Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Trier les données avant de les concaténer à l'aide de STUFF FOR XML

Essayez ceci

SELECT  ROW_NUMBER() OVER ( ORDER BY Judge.EventJudgeID ) AS JudgeRow ,
        Judge.EventID ,
        Judge.Judge_PersonID ,
        STUFF(Select ',' + CAST(Fights.FightNumber AS VARCHAR(MAX)) AS [text()] From ( SELECT DISTINCT Fights.FightNumber
                FROM    dbo.tblFights Fights ,
                        dbo.tblFightJudge FRJudge
                WHERE   Fights.FightID = FRJudge.fightid
                        AND ( Judge.Judge_PersonID = FRJudge.judge1id
                              OR Judge.Judge_PersonID = FRJudge.judge2id
                              OR Judge.Judge_PersonID = FRJudge.judge3id
                            )
                      ) X 
             ORDER BY Fights.FightNumber
             FOR
                XML PATH('')
              ), 1, 1, '') AS BoutsJudged ,
        Persons.LastName + ' ' + Persons.FirstName AS JudgeName ,
        Events.EventName ,
        Events.EventDate
FROM    dbo.tblEventJudge Judge
        INNER JOIN dbo.tblPersons Persons ON PersonID = Judge_PersonID
        INNER JOIN dbo.tblEvents Events ON Events.EventID = Judge.EventID
WHERE   Judge.EventID = 1278;

Vous pouvez vérifier ci-dessous sqls,

Avant :

Select *, 
       STUFF((Select Distinct ','+Cast(high as varchar(MAX)) 
              from master..spt_values where type = 'p' and number < 20  
              for xml Path('')),1,1,'')
from  master..spt_values where type = 'p' and number < 20

Après :

Select *, 
           STUFF((Select ','+Cast(high as varchar(MAX)) from (Select distinct     high 
    from master..spt_values where type = 'p' and number < 20) x Order by high  for xml Path('')),1,1,'')
    from  master..spt_values where type = 'p' and number < 20