我正在尝试创建一个SQL查询来解决我的问题。
我使用mysqk5.7。
我的桌子:
|project_id|start |end |cost(per month)|
|1 |2018-05-01|2018-06-30|1000 |
|2 |2018-06-01|2018-07-31|2000 |
我想通过开始和结束列生成日期列。
像这样:
|date |project_id|cost|
|2018-05|1 |1000|
|2018-06|1 |1000|
|2018-06|2 |2000|
|2018-07|2 |2000|
答案 0 :(得分:0)
这是一个单独的日期表可以使生活更加轻松的地方之一。如果您的桌子上有这样的东西:
create table DateTable(ThisDate date, Month varchar(7))
添加您可能需要的其他任何列(isWeekday等)并循环填充,然后您就可以将其用于各种事情,包括该查询。例如,您可以在其上创建一个视图以获取月,开始日期,结束日期,然后从该视图重新加入表中,以查找介于开始日期和结束日期之间的日期。
这和许多其他查询将变得简单。
create table DateTable(ThisDate date, Month varchar(7))
--- populate the table just once, re-use for all future queries
create view MonthView as
select Month,
min(ThisDate) as StartOfMonth,
max(ThisDate) as EndOfMonth
from DateTable
select Month, ProjectID, Cost
from MonthView
join MyTab on myTab.Start<=EndOfmonth and myTab.End>=StartofMonth
答案 1 :(得分:0)
创建一个表,并在每个月的第一天进行填充。您可以以编程方式执行此操作,甚至可以使用Excel生成数据并将其移植到MySQL。
create table dates (
start_date date
);
insert into dates values
('2018-04-01'),
('2018-05-01'),
('2018-06-01'),
('2018-07-01'),
('2018-8-01');
然后,您可以像这样运行查询:
查询
select
date_format(start_date, '%Y-%m') as `Date`,
a.project_id,
a.cost
from projects a
inner join dates b on b.start_date between a.start and a.end;
结果
Date project_id cost
2018-05 1 1000
2018-06 1 1000
2018-06 2 2000
2018-07 2 2000
示例
http://rextester.com/JRIUZ98116
替代
另一种选择是创建一个存储过程,该存储过程将创建一个包含日期的临时表,因此您不必生成表。可以从表中提取最小开始日期和最大结束日期,以创建临时日期表。
然后,存储过程可以执行与上述相同的联接以生成结果集。