Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum column with condition and display in row

I would like to sum a column with multiple condition and display all the result in rows

I have a table as

Status        Amount
pending         100
Success         50
pending         20
failure         80
success         20

Now I would like to find the total of pending, success and failure as

Pending        Success            failure
120             70                 80

something like

select sum(pending), sum(success), sum(failure) from mytable
like image 640
newcomer Avatar asked Sep 05 '13 05:09

newcomer


People also ask

How do I sum specific columns in a data frame?

To sum given or list of columns then create a list with all columns you wanted and slice the DataFrame with the selected list of columns and use the sum() function. Use df['Sum']=df[col_list]. sum(axis=1) to get the total sum.

How do I sum specific rows in pandas?

To sum only specific rows, use the loc() method. Mention the beginning and end row index using the : operator. Using loc(), you can also set the columns to be included. We can display the result in a new column.

How do you sum across rows in a data frame?

To sum all the rows of a DataFrame, use the sum() function and set the axis value as 1. The value axis 1 will add the row values.


1 Answers

Try this query:

SELECT
   SUM(CASE WHEN Status = 'pending' THEN Amount ELSE 0 END) AS Pending
  ,SUM(CASE WHEN Status = 'Success' THEN Amount ELSE 0 END) AS Success
  ,SUM(CASE WHEN Status = 'Failure' THEN Amount ELSE 0 END) AS Failure
FROM MyTable

You can also use this dynamic query:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN `Status` = ''',
      `Status`,
      ''' THEN Amount ELSE 0 END) AS `',
      `Status`, '`'
    )
  ) INTO @sql
FROM MyTable;

SET @sql = CONCAT('SELECT ', @sql,'
                     FROM MyTable
                  ');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See this SQLFiddle

like image 64
Himanshu Jansari Avatar answered Oct 17 '22 02:10

Himanshu Jansari