简体   繁体   中英

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. 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. 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..

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 . 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.

Obviously replace table with the actual table name.

can you use group by with col1 and col2 and sum the col3 like below

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.

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.

try out this...

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

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