简体   繁体   中英

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....

Any help would be much appreciated, Thanks :)

MasterTable.ClassYear is varchar so it will sort as a string.

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

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.

And instead of SELECT ..., "1" As [ClassYear] , write 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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