【问题标题】:How to SELECT distinct data with required ORDER?如何使用所需的 ORDER 选择不同的数据?
【发布时间】: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


【解决方案1】:

尝试使用group by。当然,天真地,这会是:

select (ca + cb) as exp, test
from table
group by (ca + cb), test
order by ord, exp

你会得到一个错误,因为ord不在selectgroup by中。所以,你需要一个聚合函数。例如:

select (ca + cb) as exp, test
from table
group by (ca + cb), test
order by min(ord), exp;

我应该注意到,您可以通过在select 中包含ord 以及select distinctgroup by 来轻松解决问题:

select distinct ca + cb as exp, test, ord
from table
order by ord, exp

【讨论】:

    【解决方案2】:

    您可以使用以下查询,

    **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 子句

    【讨论】:

      猜你喜欢
      • 2021-03-16
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      相关资源
      最近更新 更多