简体   繁体   中英

How do I fix this SQL SELECT statement for MS Access

I have the following SQL SELECT statement for MS Access that does exactly what I want when the PlayerNo field in both tables - HPFoulsPoints and VPFoulsPoints is a number type:

Select  HPFoulsPoints.*
      , 1 As OrderTbl
From    HPFoulsPoints
Union All
Select  VPFoulsPoints.*
      , 2 As OrderTbl
From    VPFoulsPoints
Order By OrderTbl
      , PlayerNo

I need to change PlayerNo field to text type, but still have the PlayerNo fields sorted by numeric value order just as above SELECT does so I thought it would be easy to just do the following:

Select  HPFoulsPoints.*
      , 1 As OrderTbl
From    HPFoulsPoints
Union All
Select  VPFoulsPoints.*
      , 2 As OrderTbl
From    VPFoulsPoints
Order By OrderTbl
      , Val(PlayerNo)

That SELECT does not work; I get the following error:

Error: -2147217913 Description: [Microsoft][ODBC Microsoft Access Driver] The ORDER BY expression (Val(PlayerNo)) 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.

How can I fix the SELECT above to use ORDER BY OrderTbl, Val(PlayerNo) to work exactly like the first SELECT at the top that works with just ORDER BY OrderTbl, PlayerNo ?

Remember I need the new SELECT where PlayerNo is a text type field to work just like the top SELECT where PlayerNo is a number type field!

I believe you just need to encapsulate everything you have (except the order by clause) in a sub query.

SELECT *
FROM (
    SELECT HPFoulsPoints.*, 1 AS OrderTbl
    FROM HPFoulsPoints
    UNION ALL
    SELECT VPFoulsPoints.*, 2 AS OrderTbl
    FROM VPFoulsPoints
    ) AS a
ORDER BY a.OrderTbl, Val(a.PlayerNo)

Edited the SQL to reflect the suggestions/corrections in comments, in case someone else stumbles across this.

Here is the final correct SQL statement:

SELECT *
FROM (
    SELECT HPFoulsPoints.*, 1 AS OrderTbl
    FROM HPFoulsPoints
    UNION ALL
    SELECT VPFoulsPoints.*, 2 AS OrderTbl
    FROM VPFoulsPoints
    ) AS a
ORDER BY a.OrderTbl, Val(a.PlayerNo)

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