我认为日历表会对您有很大帮助。
pragma foreign_keys = on;
create table calendar (
calendar_date date primary key
);
insert into calendar values ('2013-02-01');
insert into calendar values ('2013-02-02');
insert into calendar values ('2013-02-03');
insert into calendar values ('2013-02-04');
insert into calendar values ('2013-02-05');
insert into calendar values ('2013-02-06');
insert into calendar values ('2013-02-07');
insert into calendar values ('2013-02-08');
insert into calendar values ('2013-02-09');
insert into calendar values ('2013-02-10');
insert into calendar values ('2013-02-11');
insert into calendar values ('2013-02-12');
insert into calendar values ('2013-02-13');
还有一个项目表。
create table projects (
project_name varchar(16) primary key
);
insert into projects values ('Admin');
insert into projects values ('Absence');
insert into projects values ('Enhancements');
因为 SQLite 在外连接的实现上很吝啬,所以使用视图来使这更容易。
create view project_dates as
select c.calendar_date, p.project_name
from calendar c, projects p;
现在您可以从该视图中进行选择,并在从表“资源”中引入数据时使用左连接来保留这些行。我插入了一些列,这样你就可以看到发生了什么。
select p.calendar_date, p.project_name,
ifnull(sum(r.hours), 0) total_hrs,
ifnull(sum(r.hours)/40, 0) divided_hrs
from project_dates p
left join resource r
on r.date = p.calendar_date
and r.project = p.project_name
where p.calendar_date between '2013-02-03' and '2013-02-10'
group by p.calendar_date, p.project_name
order by p.calendar_date, p.project_name;
calendar_date project_name total_hrs divided_hrs
--
2013-02-03 Absence 0 0
2013-02-03 Admin 80 2
2013-02-03 Enhancements 40 1
2013-02-04 Absence 0 0
2013-02-04 Admin 0 0
2013-02-04 Enhancements 0 0
2013-02-05 Absence 0 0
2013-02-05 Admin 0 0
2013-02-05 Enhancements 0 0
2013-02-06 Absence 0 0
2013-02-06 Admin 0 0
2013-02-06 Enhancements 0 0
2013-02-07 Absence 0 0
2013-02-07 Admin 0 0
2013-02-07 Enhancements 0 0
2013-02-08 Absence 0 0
2013-02-08 Admin 0 0
2013-02-08 Enhancements 0 0
2013-02-09 Absence 0 0
2013-02-09 Admin 0 0
2013-02-09 Enhancements 0 0
2013-02-10 Absence 0 0
2013-02-10 Admin 0 0
2013-02-10 Enhancements 30 0