我创建了表格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
数据?
答案 0 :(得分:3)
尝试使用group by
。当然,天真地,这将是:
select (ca + cb) as exp, test
from table
group by (ca + cb), test
order by ord, exp
您将收到错误消息,因为ord
或select
中不存在group by
。所以,你需要一个聚合函数。例如:
select (ca + cb) as exp, test
from table
group by (ca + cb), test
order by min(ord), exp;
我应该注意,您可以通过在ord
中加select
select distinct
或group by
来轻松解决问题:
select distinct ca + cb as exp, test, ord
from table
order by ord, exp
答案 1 :(得分:0)
您可以使用以下查询
**select distinct ca + cb as exp, test, ord
from table group by test ord
order by ord, exp**
您尚未在查询中选择ord,但在 order by 子句中使用,因此会引发错误。当您汇总(总和,计数,平均,最小或最大)相对于其他列时,您必须使用 group by 子句