简体   繁体   中英

MS Access: Order by calculated field (using alias)

In a select query I calculate a field using a nested select. I would like to order the results by the calculated field (rank), however Access does not recognize the field rank. (When I run the query, Access asks for the parameter value of rank.)

SELECT
  *,
  (select count(*)
   from tbl as tbl2
   where tbl.customers > tbl2.customers and tbl.dept = tbl2.dept
  ) + 1 as rank
FROM tbl
ORDER BY rank

[The example query is taken from this post]

Use a Derived table

SELECT * FROM
(
SELECT
  *,
  (select count(*)
   from tbl as tbl2
   where tbl.customers > tbl2.customers and tbl.dept = tbl2.dept
  ) + 1 as rank
FROM tbl
) as newtbl
ORDER BY rank

Think you'd have to:

order by ((select count(*) from tbl as tbl2 where
tbl.customers > tbl2.customers and tbl.dept = tbl2.dept) + 1)

(STEP 1) Start writing an Access query that you will call QUERY1, containing the calculated field as an alias

(STEP 2) write a second query QUERY2 which references QUERY1 with the clause ORDER BY that contains the alias name you created in QUERY1

(STEP 3) test it and if it works as desired:

(STEP 4) modify QUERY2 by substituting the clause "SELECT FROM QUERY1" by the clause "SELECT FROM (XXXXX)" where XXXXX will contain all the sql statements used to define QUERY1, inserted inside the two round parenthesis. After the right parenthesis you can keep the ORDER BY statement refered to the alias fields.

That should work. Generally speaking, this technique of breaking the sql statements into Access queries that are subsequently referenced as tables and then replaced by their contained sql code, have solved many issues with complicated nested queries.

example:

Quer1 =" SELECT Tabella1.Descriz as description, Tabella1.V1, Tabella1.V2, Tabella1.V3, Sqr((Tabella1.[V1]-0.1)^2+(Tabella1.[V2]-0.7)^2+(Tabella1.[V3]-0.2)^2) AS distance FROM Tabella1 "

Quer2 (initial version) = "SELECT description, V1, V2, V3, distance FROM ( Quer1 ) ORDER BY distance ;"

Quer2 (modified version after check) = "SELECT description, V1, V2, V3, distance FROM (SELECT Tabella1.Descriz as description, Tabella1.V1, Tabella1.V2, Tabella1.V3, Sqr((Tabella1.[V1]-0.1)^2+(Tabella1.[V2]-0.7)^2+(Tabella1.[V3]-0.2)^2) AS distance FROM Tabella1 ) ORDER BY distance ;"

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