繁体   English   中英

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

[英]Order by only one, of two distinct columns

我在同一个声明中选择了ColA和ColB:

select distinct ColA, ColB, EDITABLE from TableA;

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

我试过了

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

并且当我尝试时,也看到了关于明显和秩序的这个问题

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

我无法执行上述声明。 我是SQL的新手,并且会喜欢为什么这不起作用的一些提示,并帮助我可以改进这个声明

提及所有在列Group By ,你是Select ING

在SQLServer中,它就像:

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

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

您还可以使用group by

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

这是您的查询:

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问问自己是什么使它成为必要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM