ORACLE SQL Running TOTAL and daytotal using window

2020-03-05 03:33发布

问题:

From the EMPLOYEE table, I want to group the amount of records(employees hired) AND also have the running TOTAL per day. The format of the input is like this:

rownum  Hired_date_time
1       1/10/2012 11:00
2       1/10/2012 13:00
3       20/11/2012 10:00
4       20/11/2012 15:00
5       20/11/2012 16:00
6       30/12/2012 1:00

The desired output:

Hired_date.......Hired_per_day.........TOTAL_number_of_employees
1/10/2012 ...................2 ........2
20/11/2012 ..................3 ........5
30/12/2012 ..................1 ....... 6

No problem for the GROUPING PER DAY:

select  trunc(Hired_date_time) as "Hired_date" , 
        count(*) as "Hired_per_day"
from employee
group by trunc(Hired_date_time)
order by trunc(Hired_date_time);

Question: how can I have a running total (in last column) using the window function

回答1:

select trunc(hired), 
       count(*) hired_today,       
       sum(count(*)) over (order by trunc(hired)) as running_total
from emp
group by trunc(hired)

http://sqlfiddle.com/#!4/4bd36/9



回答2:

select trunc(hire_date), 
       count(*) over (partition by trunc(hire_date)) as hired_per_day,
       count(*) over (order by hire_date) as total_number_of_employees
from employee
order by trunc(hire_date)