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

时间:2014-02-05 11:26:01

标签: sql sql-server-2012

我有这个问题:

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

将这些数据归还给我:

enter image description here

现在我需要总结每个国家每年的价值。所以每年我应该每个国家只有一次。一些帮助将不胜感激。

澄清 即,参考上面的图片,德国出现了2013年的5次,我需要一个结果显示单行“车辆Q.ty(总和x 2013) - 国家(德国) - 市场价值(总和x 2013)。美国出现2次,但两年不同,然后是2行。

1 个答案:

答案 0 :(得分:4)

你应该真正了解SQL的基础知识,而不是依赖互联网上的人来解决你的问题。

话虽这么说,要做你想做的事,你需要使用GROUP BY子句。像这样:

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