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

前端 未结 7 2062
我在风中等你
我在风中等你 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: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.

提交回复
热议问题