简体   繁体   中英

SQL ORACLE Grouping by all the days in a month

i have a table where there are two columns. One column is a timestamp, and the other one is labor hours quantity.

I need to obtain another month table, with two columns. One should be the day of the month, and the other the sum(labor) in that day.

Is easy i know, but the problem is that when there is a day without any labor, that row doesn´t appear. I need that row, with the day number and a zero as sum(labor)

Thanks for your help

the table i obtain now is

day  labor
1      8
2      4
3      7
4      3
6      7
7      9

and go on...

as you can see, the day 5 doesnt appear because this day there is no labor

I need taht day to appear like...5, Labor 0

First of all you should generate days of date range (in example between 2014 and 2015) and then left join your labor stats, shcematic example:

--generating days
WITH days AS
 (SELECT DATE '2014-01-01' + LEVEL - 1 day1
    FROM dual
  CONNECT BY LEVEL <= DATE '2015-01-01' - DATE '2014-01-01')

SELECT day.day1, NVL(sum(labor.labor),0) labot_sum FROM days
LEFT JOIN labor ON trunc(labor.timestamp_col) = days.day1
GROUP BY days.day1

EDIT

If you have integer days, generating should looks like

SELECT LEVEL day1 FROM dual CONNECT BY LEVEL <= 365

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM