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
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With