选择Distinct,按非返回列错误排序

时间:2013-03-07 19:37:18

标签: sql sql-server

假设我有下表:

Col_A:    Col_B:    Col_C:
Item1     Value1    A
Item2     Value2    B
Item3     Value3    A
Item4     Value4    B
Item5     Value5    A
Item1     Value1    A

现在,我希望得到的是来自Distinct&的Col A值。由Col B然后Col C订购Col A,结果如下:

Col_A:    Col_B:
Item1     Value1
Item3     Value3
Item5     Value5
Item2     Value2
Item4     Value4

我打算用于此的SQL是:

 SELECT DISTINCT [Col_A], [Col_B] 
 FROM [MyTable] 
      WHERE ...
 ORDER BY [Col_C] ASC, [Col_A] ASC

但我收到错误:

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

我理解为什么错误正在发生,我想用一个相当复杂的SQL / CTE解决它,但我希望有一个很好的,干净的&有效的方法来编写SQL以获得我正在寻找的结果......

3 个答案:

答案 0 :(得分:4)

您的col_c条款中没有select。使用distinct,您只能按select语句中的列进行排序。

相反,您应该使用group by声明:

select col_a, col_b
from t
group by col_a, col_b
order by max(col_c), col_a

实际上,在SQL中根本不需要select distinct。它是所有变量分组的语法简写。

答案 1 :(得分:2)

我认为现在就是这样......

SELECT  [Col_A], [Col_B]
FROM   (SELECT  [Col_A], [Col_B], Min([Col_C]) As bah
        FROM    [MyTable] 
        WHERE   ...
        Group   By [Col_A], [Col_B]) n
ORDER   BY bah ASC, [Col_A] ASC

答案 2 :(得分:0)

从yourtable中选择col_a,col_b 按col_a分组,col_b 按分钟排序(col_c),col_a

抱歉,我错过了

的订单