仅按两个不同的列中的一个排序

时间:2019-03-04 14:17:55

标签: sql oracle select

我在同一条语句中选择ColA和ColB:

select distinct ColA, ColB, EDITABLE from TableA;

我想使用ORDER BY lower(ColA),因为我想按字母顺序对ColA排序,而不考虑大写字母。 ColB不必在这种排序中受到影响,我只想对ColA进行排序(由于在ColA中有许多具有相同值的实例,因此需要区分)。

我尝试过

select distinct ColA, ColB, EDITABLE
from TableA
ORDER BY lower(ColA)

还看到了this question concerning distinct and order by,但是当我尝试

select distinct ColA, ColB, lower(ColA), EDITABLE
from TableA
GROUP BY ColA
ORDER BY lower(ColA) ASC, ColA

我无法运行上面的语句。我是SQL的新手,我很乐意为您提供一些提示,说明为什么这种方法不起作用,并为我可以改进此语句的方法提供帮助

3 个答案:

答案 0 :(得分:7)

提及Group BySelect中所有的列

在SQLServer中,它就像:

select distinct ColA, ColB, lower(ColA)
from TableA
GROUP BY ColA, ColB, lower(ColA)
ORDER BY lower(ColA) ASC

答案 1 :(得分:2)

您所引用的问题不适用于您的问题。在该问题中,还有一个另一列用于订购,其中一列不在原始select distinct中。在您的情况下,order by在原始列之一上使用函数。无需在SELECT中重复该表达式。

您也可以使用group by

select ColA, ColB, EDITABLE
from TableA
group by ColA, ColB, EDITABLE
order by lower(ColA);

答案 2 :(得分:2)

这是您的查询:

select distinct ColA, ColB, lower(ColA), EDITABLE
from TableA
GROUP BY ColA
ORDER BY lower(ColA) ASC, ColA

这就是它的作用:

1.   FROM clause: select rows from TableA.
2.   GROUP BY clause: Aggregate rows so as to get one row per ColA.
3.   SELECT clause:
3.1.   Show ColA. This is okay, ColA is what you group by.
3.2.   Show ColB. Which? There can be diferent ColB per ColA. This produces an error.
3.3.   Show lower(ColA). That is okay. You group by ColA, so lower(ColA) is also known.
3.4.   Show EDITABLE. Again: which? There can be diferent EDITABLE per ColA.
3.5.   DISTINCT: remove duplicate rows. This is superfluous, because there cannot be
       duplicate rows. They all have different ColA.
4.   ORDER BY clause:
4.1.   Sort by lower(ColA), so you have 'John' and 'john' together.
4.2.   Sort by ColA. This tells the DBMS whther to put 'John' or 'john' first.

我希望这能解释查询的执行方式,GROUP BY的作用以及SELECT子句中允许的内容。 DISTINCT通常是写得不好的查询的标志。在这里,它只是多余的,但是通常它被用作防止不良联接导致重复行的某种防御措施。每当您看到SELECT DISTINCT时都要问自己是什么使它变得必要。