Home > Software design >  sql - total avg in groupby query
sql - total avg in groupby query

Time:08-05

I want to find the avg salary for each day and in the same table I want to see the avg for all the week (total avg)

select weekday,avg(salary) as avg_salary
from table1
group by weekday

what I need to add in order to find the yellow cell?

enter image description here

CodePudding user response:

You can add the avg() regardless of weekday to your result with union all:

select weekday,avg(salary) from table1 group by weekday
union all
select max(0),avg(salary) from table1;

DBFiddle demo

Please next time pay attention to give some sample data. You can use Dbfiddle as I did.

BTW, when I started writing, I didn't see SQL server tag. Now you have it, then this is the simpler one:

select weekday,avg(salary) from table1 group by weekday with rollup

CodePudding user response:

You can use GROUPING SETS for this.

select
  weekday,
  avg(salary) as avg_salary
from table1
group by grouping sets (
    (weekday),
    ()
);

db<>fiddle

ROLLUP also works, but is less flexible.

  • Related