如何 SELECT 具有所需 ORDER 的不同数据?
How to SELECT distinct data with required ORDER?
我已经创建了 table 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
收到错误:
ORDER BY items must appear in the select list if SELECT DISTINCT is specified. `
还尝试使用内部查询作为
select exp, test
from ( select distinct ca + cb as exp, ord, test
from ttemp
order by ord, exp)
收到错误:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
我怎样才能 select distinct
需要 ORDER
的数据?
尝试使用 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;
我应该注意到,您可以通过在 select
中包含 ord
,使用 select distinct
或 group by
:
来轻松解决问题
select distinct ca + cb as exp, test, ord
from table
order by ord, exp
您可以使用以下查询,
**select distinct ca + cb as exp, test, ord
from table group by test ord
order by ord, exp**
您没有在查询中选择 ord,但在 order by 子句中使用,因此会抛出错误。第二件事,当你对其他列进行聚合(sum、count、avg、min 或 max)时,你必须使用 group by 子句
我已经创建了 table 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
收到错误:
ORDER BY items must appear in the select list if SELECT DISTINCT is specified. `
还尝试使用内部查询作为
select exp, test
from ( select distinct ca + cb as exp, ord, test
from ttemp
order by ord, exp)
收到错误:
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.
我怎样才能 select distinct
需要 ORDER
的数据?
尝试使用 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;
我应该注意到,您可以通过在 select
中包含 ord
,使用 select distinct
或 group by
:
select distinct ca + cb as exp, test, ord
from table
order by ord, exp
您可以使用以下查询,
**select distinct ca + cb as exp, test, ord
from table group by test ord
order by ord, exp**
您没有在查询中选择 ord,但在 order by 子句中使用,因此会抛出错误。第二件事,当你对其他列进行聚合(sum、count、avg、min 或 max)时,你必须使用 group by 子句