[英]SQL Using ORDER BY with UNION doesn't sort numbers correctly (e.g. 10 before 8)
I've tried looking for the answer, and read many threads on this site, but still can't find the answer I'm looking for. 我尝试寻找答案,并阅读了本网站上的许多主题,但仍然找不到我想要的答案。
I am trying to sort a series of numbers that are real look-ups and also one * which isn't, I can sort fine when I don't need to add the fake * but not after. 我正在尝试对一系列数字进行排序,这些数字是真正的查找,而一个*不是。当我不需要添加假*时,我可以进行很好的排序,但以后不要。
I have tried 我努力了
SELECT DISTINCT MasterTable.ClassName, MasterTable.ClassYear
FROM MasterTable
UNION ALL
SELECT DISTINCT "*" As [ClassName], "1" As [ClassYear]
FROM MasterTable
ORDER BY MasterTable.ClassYear;
And 和
SELECT DISTINCT MasterTable.ClassName, MasterTable.ClassYear
FROM (
SELECT DISTINCT MasterTable.ClassName, MasterTable.ClassYear FROM MasterTable
UNION
SELECT DISTINCT "*" As [ClassName], "1" As [ClassYear] FROM MasterTable
)
ORDER BY MasterTable.ClassYear;
But both return the ClassYear as 1, 10, 12, 8... rather than 1, 8, 10, 12.... 但是两者都将ClassYear返回为1、10、12、8 ...,而不是1、8、10、12...。
Any help would be much appreciated, Thanks :) 任何帮助将不胜感激,谢谢:)
MasterTable.ClassYear is varchar so it will sort as a string. MasterTable.ClassYear是varchar,因此它将作为字符串排序。
You'll have to convert it in the query or fix the column type. 您必须在查询中将其转换或修复列类型。
For the 2nd clause, you also need only: 对于第二个子句,您还只需要:
SELECT "*" As [ClassName], "1" As [ClassYear] --No FROM MasterTable
However, you can "cheat" and do this. 但是,您可以“作弊”并执行此操作。 Here 1 will be int and will force a conversion to int from the 1st clause because
这里1将是int,将强制从第一个子句转换为int,因为
SELECT "*" As [ClassName], 1 As [ClassYear] --force int. And fixed on edit
UNION ALL
SELECT DISTINCT MasterTable.ClassName, MasterTable.ClassYear
FROM MasterTable
ORDER BY ClassYear; --no table ref needed
It's property sorting those values as strings. 它是将这些值作为字符串排序的属性。 If you want them in numerical order, try something like
Cast(MasterTable.ClassYear AS int)
, either in the select or in the order by, or both, depending on how you end up structuring your query. 如果您希望按数字顺序排列它们,请根据选择的结构或查询顺序,依次选择
Cast(MasterTable.ClassYear AS int)
或按select或by或按两者的顺序。
And instead of SELECT ..., "1" As [ClassYear]
, write SELECT ..., 1 As [ClassYear]
. 而不是
SELECT ..., "1" As [ClassYear]
,将SELECT ..., 1 As [ClassYear]
写SELECT ..., 1 As [ClassYear]
。
You are returning the year as a string, not a number. 您以字符串而不是数字的形式返回年份。 That means that it's sorted as text, not numerically.
这意味着它是按文本而不是数字排序的。
Either return the year as a number, or convert the value into a number when sorting it. 请以数字形式返回年份,或者在对值进行排序时将其转换为数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.