简体   繁体   中英

sql/access_order by sum of rows_select top

I have searched for an answer here, but have not found yet. I have a table It has 8 columns.

Company_code - integer
Company name - text
Product code - integer
Product description - text
Cost of every transaction - double 
Weight - double
Country of origin - text 

Here is a link to an access document http://we.tl/3yjzrXW5Bc Every row is an import transaction every company did. There are many rows for every company code. I need to choose top 20 companies by sum of cost of every transaction . I need to ORDER companies by their SUM (cost).

I tried many queries but none worked. I ended up with this

SELECT *
  FROM groupping
 ORDER BY sum([cost]) DESC;

I am learning sql ad It would be grateful if you could help me.

You can query the sum (with grouping), order by it, and apply top :

SELECT   TOP 20 company_name, SUM(cost)
FROM     groupping
GROUP BY company_name
ORDER BY 2 DESC 

You need 2 queries :

  • one to do the sum by company (as shown by Mureinik with the code instead of the name of the company)
  • one to get your result, with all your columns both are linked with the company_code (I presume this is the primary key)

But beware : ONE query is made to answer ONE question. Having the weight in the same row than the sum of the cost will probably give a unwanted result. Try to represent want you want with a small (but representative) set of data in Excel to fix up your idea.

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