I have a table:
------------------------
|id|p_id|desired|earned|
------------------------
|1 | 1 | 5 | 7 |
|2 | 1 | 15 | 0 |
|3 | 1 | 10 | 0 |
|4 | 2 | 2 | 3 |
|5 | 2 | 2 | 3 |
|6 | 2 | 2 | 3 |
------------------------
I need to make some calculations, and try to make it in one not really complex request, otherwise I know how to calculate it with numbers of requests. I need resulted table like following:
---------------------------------------------------------
|p_id|total_earned| AVG | Count | SUM |
| | | (desired)|(if earned != 0)|(desired)|
---------------------------------------------------------
| 1 | 7 | 10 | 1 | 30 |
| 2 | 9 | 2 | 3 | 6 |
---------------------------------------------------------
I build so far:
SELECT p_id, SUM(earned), AVG(desired), Sum(desired)
FROM table GROUP BY p_id
But I can't figure out how to calculate the number of grouped records with conditions. I can get this number with HAVING
but in separated request.
I almost sure what SQL should have this power.
The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.
SQL SUM() and COUNT() using variable SUM of values of a field or column of a SQL table, generated using SQL SUM() function can be stored in a variable or temporary column referred as alias. The same approach can be used with SQL COUNT() function too.
Use DataFrame. groupby(). sum() to group rows based on one or multiple columns and calculate sum agg function. groupby() function returns a DataFrameGroupBy object which contains an aggregate function sum() to calculate a sum of a given column for each group.
When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.
You can use CASE
expression for this.
Try this,
SELECT p_id
,SUM(earned) AS total_earned
,AVG(desired) AS avg_desired
,COUNT(CASE WHEN Earned!=0 THEN 1 END) AS earned_count
,SUM(desired) AS sum_desired
FROM table
GROUP BY p_id;
A shorter alternative to CASE
is
SELECT p_id,
SUM(earned) AS total_earned,
AVG(desired) AS average_desired,
COUNT(earned != 0 OR NULL) AS earned_count,
SUM(desired) AS sum_desired
FROM table GROUP BY p_id;
because NULL
s are not counted.
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