views:

45

answers:

3

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 :)

+1  A: 

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.

Guffa
@Tim: "1" will be converted to the datatype of the columns because int has higher precedence than varchar. Unless I'm missing something, the table column should be varchar
gbn
@Tim: If the field is a number in the database, then it's the `"1"` value in the second query that determines the data type. If you change it to `1`, the data type will stay numerical.
Guffa
I missed that. Thank you both :)
Tim
@Guffa: `SELECT 1 AS foo UNION ALL SELECT 'bar'` = fail. The precedence is over all UNION clauses, not the last one. Also fail: `SELECT 'bar' AS foo UNION ALL SELECT 1`
gbn
@gbn: That is true for an SQL Server database, but that's not what's used here. Notice the quotation marks used as string delimiters.
Guffa
SET QUOTED_IDENTIFIER OFF ?
gbn
+2  A: 

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

Eric Mickelsen
It works now, thanks! :)
Tim
+4  A: 

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
gbn
I need to put "FROM MasterTable" in above the Union all, but it works now. Thanks :)
Tim
Remove DISTINCT from above the UNION ALL sorry
gbn