SQL 服务器 Select 唯一 ID 无效

SQL SERVER Select Distinct ID is not working

我正在尝试理解下面的 sql Select 声明,但我无法理解。

Select DISTINCT vc.cid, vt.tid, vc.device,
    STUFF((select ', ' + c.tName from thumbTbl t2
                    join tags v ON t2.cid = v.cid
                    join config c on v.tid = c.tid
                    where vc.cid = t2.cid
                    group by c.tName 
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(max)'), 1, 1, '') tName
from tags vt
    Inner join thumbTbl vc on vt.cid = vc.cid
    Left join config vtc on vt.tid = vtc.tid
order by vc.cid asc

结果如下:

cid tid device      tName
--- --- ---------   ---------
159 7   Mat Dwens    Escalation, Follow Up, More Benefits
159 11  Mat Dwens    Escalation, Follow Up, More Benefits
159 12  Mat Dwens    Escalation, Follow Up, More Benefits
160 7   Jeniffer P    Rectro
162 8   Marc Novice   More Benefits, Rectro
162 6   Marc Novice   More Benefits, Rectro
165 4   Jeniffer P    Follow up

问题:如何只显示每个 Selected Id 的 1 行?,我尝试使用 SELECT DISTINCT 但仍然给了我相同的结果。

我想看到的结果必须如下所示:

cid tid device      tName
------- ---------   ----------
159 12  Mat Dwens   Escalation, Follow Up, More Benefits
160 7   Jeniffer P  Rectro
162 8   Marc Novice More Benefits, Rectro
165 4   Jeniffer P  Follow up

有人知道吗?

您要的不是 DISTINCT,而是 GROUP BYtid 上的聚合函数。结果 DISTINCT 因为每一行的 tid 值不同,但是,您想要的是MAX。由于缺少样本数据,这是未经测试的,但是,我认为这是正确的:

SELECT vc.cid,
       MAX(vt.tid) AS tid,
       vc.device,
       STUFF((SELECT ', ' + c.tName
              FROM thumbTbl t2
                   JOIN tags v ON t2.cid = v.cid
                   JOIN config c ON v.tid = c.tid
              WHERE vc.cid = t2.cid
              GROUP BY c.tName
             FOR XML PATH(''), TYPE).value('(./text())[1]', 'nvarchar(max)'),1,2,'') AS tName --Changed to use .text() and also removed leading space
FROM tags vt
     INNER JOIN thumbTbl vc ON vt.cid = vc.cid
     LEFT JOIN config vtc ON vt.tid = vtc.tid
GROUP BY vc.cid,
         vc.device
ORDER BY vc.cid ASC;

删除外部查询中的 SELECT DISTINCT 和与 config 的连接。然后修复内部查询,使其仅从 config:

中获取您想要的内容
select vc.cid, vt.tid, vc.device,
       stuff((select ', ' + c.tName
              from config c on v.tid = c.tid
              where v.tid = c.tid
              for xml path(''), TYPE
             ).value('.', 'NVARCHAR(max)'
                    ), 1, 1, ''
            ) tNames
from tags vt join
     thumbTbl vc
     on vt.cid = vc.cid
group by vc.cid, vt.tid, vc.device
order by vc.cid asc