Since you have agents working in two different groups, you will need two different queries. The main group is grouped by dt to get row values ββper day. Another request is to execute the AVG() and COUNT() aggregates for the entire set of rows.
To use them simultaneously, you need to join them together. But since there is no real connection between the two queries, this is a Cartesian product, and we will use CROSS JOIN . Effectively, which concatenates each row of the main query with one row received by the aggregated query. You can then do the arithmetic in the SELECT list using the values ββof both:
So, based on the request from your earlier question:
SELECT indxs.*, ((indx_val2 - indx_val2_avg) * (indx_val1 - indx_val1_avg)) / total_rows AS cv FROM ( SELECT dt, MAX(CASE WHEN indx_nm = 'ABQI' THEN indx_nm ELSE NULL END) AS indx_nm1, MAX(CASE WHEN indx_nm = 'ABQI' THEN indx_val ELSE NULL END) AS indx_val1, MAX(CASE WHEN indx_nm = 'ACNACTR' THEN indx_nm ELSE NULL END) AS indx_nm2, MAX(CASE WHEN indx_nm = 'ACNACTR' THEN indx_val ELSE NULL END) AS indx_val2 FROM table1 a GROUP BY dt ) indxs CROSS JOIN ( SELECT 'ABQI' AS indx_nm1_aname, AVG(CASE WHEN indx_nm = 'ABQI' THEN indx_val ELSE NULL END) AS indx_val1_avg, 'ACNACTR' AS indx_nm2_aname, AVG(CASE WHEN indx_nm = 'ACNACTR' THEN indx_val ELSE NULL END) AS indx_val2_avg, COUNT(*) AS total_rows FROM table1 b WHERE indx_nm IN ('ABQI','ACNACTR') ) aggs WHERE indx_nm1 IS NOT NULL AND indx_nm2 IS NOT NULL ORDER BY dt
Here is a demo built on your previous one: http://sqlfiddle.com/#!6/2ec65/14
source share