简体   繁体   中英

SQL query with Inner Join, aggregation and sum

I have this query:

SELECT Projects.proj_num_of_vehicles AS VehicQuantity
 , customers.cust_country AS Country
 , Projects.proj_contract_value AS MarketValue
 , Projects.proj_date AS Year

FROM
  dbo.Projects

  INNER JOIN dbo.Manufacturers
    ON Projects.proj_man_id = Manufacturers.man_id
  INNER JOIN dbo.customers
    ON Projects.proj_cust_id = customers.cust_id

ORDER BY
  year DESC

which is returning me these data:

在此处输入图片说明

Now I need to sum-up values per country per year. So I should get each country only once per year. Some help will be appreciated.

Clarification Ie, referring to the picture above for Germany, which is appearing 5 times in 2013, I need a result showing a single line "Vehicles Q.ty(sum x 2013) -Country (Germany) -Market Value(sum x 2013). United States appears 2 times but are two different years then 2 lines.

You should really read up on the basics of SQL, instead of relying on people on the internet to solve your problems just like that.

That being said, to do what you want, you need to use the GROUP BY clause. Something like this:

SELECT SUM(Projects.proj_num_of_vehicles) AS VehicQuantity
 , customers.cust_country AS Country
 , SUM(Projects.proj_contract_value) AS MarketValue
 , YEAR(Projects.proj_date) AS Year

FROM
  dbo.Projects

  INNER JOIN dbo.Manufacturers
    ON Projects.proj_man_id = Manufacturers.man_id
  INNER JOIN dbo.customers
    ON Projects.proj_cust_id = customers.cust_id
GROUP BY
   customers.cust_country, YEAR(Projects.proj_date)
ORDER BY
  year DESC

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