简体   繁体   English

如何在SELECT中没有列的情况下排序BY

[英]How to Order BY without having Column in SELECT

I am using MS-SQL and I have a table like this: 我正在使用MS-SQL,我有一个这样的表:

Count  Code
1      A
2      C
3      A
4      B
5      C
6      B

I need to only to get Distinct Row of the Code Column but I need to keep the Order of the Column to create a Comma Delimited String like this: 我只需要获取Code列的Distinct Row,但我需要保持Column的顺序以创建一个逗号分隔的字符串,如下所示:

    A, C, B

I have tried the following code to not get an SQL Error of Msg 145, Level 15 - ORDER BY items must appear in the select list if SELECT DISTINCT is specified. 我已经尝试以下代码来获取Msg 145的SQL错误,等级15 - 如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。

SELECT @tlist = ISNULL(@tlist+', ','') + Code 
FROM (SELECT DISTINCT t.Code  
     FROM @Table t) 

but I get an output of A, B, C 但我得到了A,B,C的输出

So, you don't want distinct . 所以,你不希望distinct You want group by : 你想要group by

select t.code
from @Table t
group by t.code
order by min(count)

You can order by columns not mentioned in the select clause. 您可以按select子句中未提及的列进行排序。

To get the comma delimited list as a single variable, use this technique: 要将逗号分隔列表作为单个变量,请使用以下技术:

select stuff((select ', '+t.code
              from @Table t
              group by t.code
              order by min(count)
              for xml path ('')
             ), 1, 2, '')

Order by in a subquery is generally undefined. Order by子查询通常是不确定的。 And, your method of concatenating the list together in order is not guaranteed to work. 并且,无法保证按顺序将列表连接在一起的方法。

order them in your subquery 在子查询中对它们进行排序

SELECT DISTINCT t.Code  
FROM @Table t
ORDER BY t.Code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM