MS-Access -> SELECT AS + ORDER BY = error

前端 未结 7 2030
我在风中等你
我在风中等你 2020-12-07 01:52

I\'m trying to make a query to retrieve the region which got the most sales for sweet products. \'grupo_produto\' is the product type, and \'regiao\' is the region. So I got

相关标签:
7条回答
  • 2020-12-07 02:14

    You can do it like this

    select * from(
      select a + b as c, * from table)
      order by c
    

    Access has some differences compared to Sql Server.

    0 讨论(0)
  • 2020-12-07 02:18

    Try using a subquery and order the results in an outer query.

    SELECT TOP 1 * FROM
    (
        SELECT
            r.nm_regiao, 
            (SELECT COUNT(*)
             FROM Dw_Empresa
             WHERE grupo_produto='1' AND cod_regiao = d.cod_regiao) as total 
        FROM Dw_Empresa d
        INNER JOIN tb_regiao r ON r.cod_regiao = d.cod_regiao
    ) T1
    ORDER BY total DESC
    

    (Not tested.)

    0 讨论(0)
  • 2020-12-07 02:19

    Old Question I know, but it may help someone knowing than while you cant order by aliases, you can order by column index. For example, this will work without error :

    SELECT 
     firstColumn,
     IIF(secondColumn = '', thirdColumn, secondColumn) As yourAlias
    FROM
     yourTable
    ORDER BY
     2 ASC
    

    The results would then be ordered by the values found in the second column wich is the Alias "yourAlias".

    0 讨论(0)
  • 2020-12-07 02:24

    Aliases are only usable in the query output. You can't use them in other parts of the query. Unfortunately, you'll have to copy and paste the entire subquery to make it work.

    0 讨论(0)
  • 2020-12-07 02:25

    I suggest using an intermediate query.

     SELECT r.nm_regiao, d.grupo_produto, COUNT(*) AS total
       FROM Dw_Empresa d INNER JOIN tb_regiao r ON r.cod_regiao = d.cod_regiao
       GROUP BY r.nm_regiao, d.grupo_produto;
    

    If you call that GroupTotalsByRegion, you can then do:

    SELECT TOP 1 nm_regiao, total FROM GroupTotalsByRegion 
      WHERE grupo_produto = '1' ORDER BY total DESC
    

    You may think it's extra work to create the intermediate query (and, in a sense, it is), but you will also find that many of your other queries will be based off of GroupTotalsByRegion. You want to avoid repeating that logic in many other queries. By keeping it in one view, you provide a simplified route to answering many other questions.

    0 讨论(0)
  • 2020-12-07 02:33

    How about:

    SELECT TOP 1  r.nm_regiao 
    FROM (SELECT Dw_Empresa.cod_regiao, 
                 Count(Dw_Empresa.cod_regiao) AS CountOfcod_regiao
          FROM Dw_Empresa
          WHERE Dw_Empresa.[grupo_produto]='1'
          GROUP BY Dw_Empresa.cod_regiao
          ORDER BY Count(Dw_Empresa.cod_regiao) DESC) d
    INNER JOIN tb_regiao AS r 
    ON d.cod_regiao = r.cod_regiao
    
    0 讨论(0)
提交回复
热议问题