简体   繁体   English

列值匹配时的SQL sum字段

[英]SQL sum field when column values match

The title was hard to word but the question is pretty simple. 标题很难说,但问题很简单。 I searched all over here and could not find something for my specific issue so here it is. 我到处搜索,找不到适合我的特定问题的东西,所以就在这里。 I'm usuing Microsoft SQL Server Management Studio 2010. 我正在使用Microsoft SQL Server Management Studio 2010。

Table Currently looks like this 表格目前看起来像这样

  | Value | Product Name|
  |  300  | Bike        |
  |  400  | Bike        |
  |  300  | Car         |
  |  300  | Car         |

I need the table to show me the sum of Values where Product Name matches - like this 我需要表格来显示产品名称匹配的值的总和-像这样

  | TOTAL | ProductName |
  |  700  | Bike        |
  |  600  | Car         |

I've tried a simple 我尝试了一个简单的

 SELECT
      SUM(Value) AS 'Total'
      ,ProductName
 FROM TableX

But the above doesn't work. 但是以上方法不起作用。 I end up getting the sum of all values in the column. 我最终得到列中所有值的总和。 How can I sum based on the product name matching? 如何根据产品名称匹配求和?

Thanks! 谢谢!

SELECT SUM(Value) AS 'Total', [Product Name]
FROM TableX  
GROUP BY [Product Name]

SQL Fiddle Example SQL小提琴示例

Anytime you use an aggregate function, ( SUM , MIN , MAX ... ) with a column in the SELECT statement, you must use GROUP BY . 每当您在SELECT语句中的列上使用聚合函数( SUMMINMAX ...)时,都必须使用GROUP BY This is a group function that indicates which column to group the aggregate by. 这是一个组函数,用于指示要对汇总进行分组的列。 Further, any columns that are not in the aggregate cannot be in your SELECT statement. 此外,不在聚合中的任何列都不能在SELECT语句中。

For example, the following syntax is invalid because you are specifying columns ( col2 ) which are not in your GROUP BY (even though MySQL allows for this): 例如,以下语法无效,因为您要指定不在GROUP BY列( col2 )(即使MySQL允许这样做):

SELECT col1, col2, SUM(col3)
FROM table
GROUP BY col1

The solution to your question would be: 您的问题的解决方案是:

SELECT ProductName, SUM(Value) AS 'Total'
FROM TableX
GROUP BY ProductName

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

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