简体   繁体   English

如何基于SQL中两列的值获取一列的总和

[英]How to get sum of a column based on the values of two columns in SQL

I have a table as bellow with 3 columns. 我有一张桌子,下面有3列。 Sample data is given 给出了样本数据

column_1    column_2    column_3
   A           a           10
   A           b           20
   B           a           10
   A           a           10
   B           a           30
   A           b           40
   A           c           10
   C           a           20   

I want to get the sum of column_3 based on the values of column_1 and column_2. 我想基于column_1和column_2的值获取column_3的总和。 Which means I want to get the sum of values in column_3 which are having 'A' for column_1 'a' for column_2 and so on.. 这意味着我想获得column_3中的值之和,其中column_1为'A',column_2为'a',依此类推。

Sample output is given bellow
     column_1    column_2    SUM(column_3)
       A           a              20
       A           b              60
       A           c              10
       B           a              40
       C           a              20        

Can someone please tell me how to do this 有人可以告诉我该怎么做吗

Try this: 尝试这个:

SELECT SUM(column_3), column_1, column_2 FROM table GROUP BY column_1, column_2

The GROUP BY command states that you want to group the aggregate function ( SUM ) using distinct values of the columns which names follow the GROUP BY . GROUP BY命令指出您要使用名称跟随GROUP BY的列的不同值对聚合函数( SUM )进行分组。 It is not "required" that they also appear in the SELECT portion of the query, but it is good practice (and the only way of knowing which row represents which grouping. 并非“必需”它们也出现在查询的SELECT部分中,但这是一种好习惯(也是知道哪一行代表哪个分组的唯一方法)。

Obviously replace table with the actual table name. 显然用实际的表名替换table

can you use group by with col1 and col2 and sum the col3 like below 您可以通过col1和col2使用group by并按如下所示对col3求和

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

select column_1, column_2, SUM(column_3) from table group by column_1, column_2

group by allows you to apply an aggregate function to a column based on groupings of other columns. group by允许您基于其他列的分组将聚合函数应用于列。

Thinking backwards, group by column_1, column_2 can be thought of as: "give me all unique combinations of column_1 and column_2. Selecting SUM(column_3) will then take the sum of the entries in column_3 for each group. group by column_1, column_2可以认为是:“给我列_1和列_2的所有唯一组合。然后选择SUM(column_3)将为每个组取column_3中条目的总和。

try out this... 试试这个...

SELECT SUM(column_3), column_1, column_2 FROM table   
GROUP BY column_1, column_2

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

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