【发布时间】:2017-01-05 12:54:28
【问题描述】:
我已经创建了表 t1(ca char(1), cb char(10), test char(20), ord char(20)),我想通过 ord 的顺序获得不同的 ca+cb。
为了获取数据,我将查询编写为:
select distinct ca + cb as exp, test
from table
order by ord, exp
收到错误:
如果指定了 SELECT DISTINCT,则 ORDER BY 项目必须出现在选择列表中。 `
也尝试使用内部查询作为
select exp, test
from ( select distinct ca + cb as exp, ord, test
from ttemp
order by ord, exp)
收到错误:
ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效,除非还指定了 TOP、OFFSET 或 FOR XML。
如何选择 distinct 所需的 ORDER 数据?
【问题讨论】:
-
好吧,你有它,除非你在
ord上使用聚合函数 -
使用
order by ca+cb,否则不能使用。如果您想按 ord 排序,请将ord添加到选定字段,例如:select distinct ca + cb as exp, test, ord from table order by ord, ca+cb。 -
在您的第一个查询中,您只需在您的选择列表中添加 ord,然后它应该可以工作
-
@nick_n_a & @Stephan 无法在选择字段中添加
ord -
您将需要添加 MIN/MAX Ord,否则将使用找到的重复项中的哪个值
标签: sql sql-server sql-order-by rdbms