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.