[英]How do I order by a column in a subquery with a distinct clause?
I have an extremely large query that I need to include a comma delimited list in. I'm accomplishing this with subqueries like so: 我有一个非常大的查询,需要在其中包含一个以逗号分隔的列表。我正在使用类似以下的子查询来完成此操作:
STUFF(( SELECT distinct ',' + t1.Name
FROM t2
inner join t1 ON t1.ID = t2.ID
WHERE t2.otherField = 12345
ORDER BY t2.ID
FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, '') as talentName
In this particular case I need to add a distinct clause (as shown). 在这种特殊情况下,我需要添加一个独特的子句(如图所示)。 However, when I do so I get the following error:
但是,当我这样做时,出现以下错误:
Msg 145, Level 15, State 1, Line 2
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
I understand why this error occurs, but I'm not sure what to do about it. 我知道为什么会发生此错误,但是我不确定该怎么办。 t2.ID cannot be included in the select statement as it would then get returned as part of the resultset.
t2.ID不能包含在select语句中,因为它随后将作为结果集的一部分返回。 I cannot remove the order by clause because the comma delimited list must be in an order that matches another list I'm generating of the IDs.
我无法删除order by子句,因为逗号分隔的列表必须与我正在生成的ID的另一个列表相匹配的顺序。
How can I insure that this comma delimited list is both distinct and in the proper order? 如何确保此逗号分隔的列表是不同的且顺序正确?
End Goal 最终目标
To help clarify what I'm trying to accomplish, this query will pull comma delimited lists of both the t1.name and t1.ID. 为了帮助阐明我要完成的工作,此查询将拉出逗号分隔的t1.name和t1.ID列表。 I'm currently doing this in two separate STUFF statements, but if there is an alternate method I'd be open to it.
我目前正在两个单独的STUFF语句中执行此操作,但是如果有其他方法,我将对其开放。 This query will return several thousand rows, so I'm attempting to find a set-based solution to avoid thousands of ad-hoc queries running each time our web page is loaded.
该查询将返回数千行,因此,我试图找到一种基于集合的解决方案,以避免每次加载网页时都运行数千个即席查询。
You can use a derived table with a GROUP BY
as below. 您可以使用带有
GROUP BY
的派生表,如下所示。 t1.ID
is included in the group by on the assumption that it is the PK of table1 so this will correctly distinguish different individuals with the same name. t1.ID
是表1的PK, t1.ID
其包括在组中,因此可以正确地区分具有相同名称的不同个人。
SELECT STUFF(
(
SELECT ',' + t1Name
FROM (SELECT t1.Name AS t1Name,
min(t2.ID) AS t2ID
FROM t2
INNER JOIN t1
ON t1.ID = t2.ID
WHERE t2.otherField = 12345
GROUP BY t1.ID,
t1.Name) x
ORDER BY t2ID
FOR XML PATH('')
, TYPE).value('.','VARCHAR(max)')
, 1, 1, '') as talentName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.