如何通过链接 table 按 nulls-last 排序

How to order by nulls-last by a linked table

我有两个表 PersonPersonSkill

ID NAME
1 Person 1
2 Person 2
3 Person 3

个人技能

PERSON_ID SKILL SORT
1 Sing 20
1 Playful 10
2 Sing 10
1 Bowl 30
1 SQL 40

我正在尝试编写一个顺序,按字母顺序对人员进行技能排序,但最后为空值。

正在寻找这样的东西:

SELECT distinct
  p.*,
  STUFF(
    (SELECT ',' + ps.SKILL
      FROM PersonSkill ps
      WHERE ps.PERSON_ID = p.ID
      ORDER BY ps.SORT
      FOR XML PATH('')
    ), 1, 1, '') sortRule
FROM Person p
ORDER BY IIF(sortRule is null, 1, 0) asc, sortRule asc

但出于某种原因,我无法在 ORDER BY 中的 IIFcase 操作中使用 sortRule,因为它给我这个错误:Invalid column name 'sortRule'.

如果我从 select 语句中删除 STUFF sortRule,它会告诉我在与 distinct 一起使用时它必须存在。我也不能只将 STUFF 复制到订单中,因为它会说:ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

当您执行字符串聚合时,您应该使用 GROUP BY,而不是 DISTINCT。至于按 sortRule 排序,您不能在 ORDER BY 的表达式中包含列的别名。因此,一种方法是使用 CTE:

WITH CTE AS(
    SELECT p.Id,
           p.[Name],
           STUFF((SELECT ',' + ps.SKILL
                  FROM dbo.PersonSkill ps
                  WHERE ps.PERSON_ID = p.ID
                  ORDER BY ps.SORT
                  FOR XML PATH(''),TYPE).value('(./text())[1]','varchar(MAX)'),1,1,'') AS sortRule
    FROM dbo.Person p
    GROUP BY p.Id,
             p.[Name])
SELECT *
FROM CTE
ORDER BY CASE WHEN sortRule IS NULL THEN 1 ELSE 0 END,
         sortRule;

db<>fiddle