简体   繁体   English

具有内部联接,聚合和求和的SQL查询

[英]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. 澄清一点,即上面提到的德国图片,该图片在2013年出现了5次,我需要显示一个结果行“车辆数量(总和x 2013)-国家(德国)-市场价值(总和x 2013)美国出现了2次,但分别是两个不同年份的2行。

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. 您应该真正阅读SQL的基础知识,而不是依靠互联网上的人来解决您的问题。

That being said, to do what you want, you need to use the GROUP BY clause. 话虽如此,要做您想做的事,您需要使用GROUP BY子句。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM