简体   繁体   中英

How to order (sort) formatted numbers in an Access Union Query (SQL)

I've created the following Union Query in Access, but I'm having trouble ordering the "hourly" values when they are formatted the way I wish. Because the query of the Emp_Police table returns no records (due to the Like "SP*" filter), I get an error of:

"The ORDER BY expression (Hourly) includes fields that are not selected by the query. Only those fields requested in the first query can be included in an ORDER BY expression."

The ORDER BY expression works when the fields are not formatted but not when they are. I've also tried the ORDER BY expression as

ORDER BY Format([Hourly],"Standard") DESC 

but that doesn't seem to work either.

SELECT Emp_Norm.UnionCode, Emp_Norm.EMPNAME, Format([Hourly],"Standard") AS Expr1, Format([Salary],"Standard") AS Expr2
FROM Emp_Norm
WHERE (((Emp_Norm.UnionCode) Like "SP*"))
UNION
SELECT Emp_Police.UnionCode, Emp_Police.EMPNAME, Format([Hourly],"Standard") AS Expr1, Format([Salary],"Standard") AS Expr2
FROM Emp_Police
WHERE (((Emp_Police.UnionCode) Like "SP*"))
ORDER BY Hourly DESC;

As a smaller issue, the formatted numbers are left justified as if they are text not right justified as numbers should be.

You can include Hourly in the subqueries:

SELECT Emp_Norm.UnionCode, Emp_Norm.EMPNAME, Format([Hourly],"Standard") AS Expr1, Format([Salary],"Standard") AS Expr2,
       Hourly
FROM Emp_Norm
WHERE (((Emp_Norm.UnionCode) Like "SP*"))
UNION
SELECT Emp_Police.UnionCode, Emp_Police.EMPNAME, Format([Hourly],"Standard") AS Expr1, Format([Salary],"Standard") AS Expr2,
       Hourly
FROM Emp_Police
WHERE (((Emp_Police.UnionCode) Like "SP*"))
ORDER BY Hourly DESC;

In MS Access, the columns used in the ORDER BY for a UNION / UNION ALL need to be selected.

Changing the final line to

ORDER BY Expr1 DESC

works.

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