我想在mysql中执行一个爆炸式的任务,我需要在每天从开始和结束日期创建新记录。
目前的数据如下:
Person, Start Date, End Date, Score
a , 12/05/2017, 14/05/2017, 0.8
a , 15/05/2017, 17/07/2017, 0.3
b , 12/05/2017, 14/05/2017, 0.5
b , 15/05/2017, 17/07/2017, 0.2
现在,我需要重新创建数据
Person, Date, Score
a , 12/05/2017, 0.8
a , 13/05/2017, 0.8
a , 14/05/2017, 0.8
a , 15/05/2017, 0.3
a , 16/05/2017, 0.3
a , 17/05/2017, 0.3
b , 12/05/2017, 0.5
b , 13/05/2017, 0.5
b , 14/05/2017, 0.5
b , 15/05/2017, 0.2
b , 16/05/2017, 0.2
b , 17/05/2017, 0.2
因为,我将此表与其他表格一起加入日期和时间表。 person列,需要此操作。我怎么能在MySQL中做到这一点?
答案 0 :(得分:0)
您可以使用以下查询来获得结果 -
create table PersonTable (
Person varchar(10), StartDate date , EndDate date, Score float
)
go
insert into PersonTable
select 'a' , '2017-05-12', '2017-05-14', 0.8
union all select 'a' , '2017-05-15', '2017-07-17', 0.3
union all select 'b' , '2017-05-12', '2017-05-14', 0.5
union all select 'b' , '2017-05-15', '2017-07-17', 0.2
create table #DateList (Date_Time date)
declare @MinDt Date , @MaxDt Date
select @MinDt= Min(StartDate) , @MaxDt = Max(EndDate) from PersonTable
while (@MinDt < = @MaxDt)
begin
insert into #DateList
select @MinDt
select @MinDt = dateadd(day,1, @MinDt)
end
select t1.Person , t2.Date_Time , t1.Score from PersonTable t1
join #DateList t2 on
t1.StartDate <= t2.Date_Time
and t1.EndDate >=t2.Date_Time
答案 1 :(得分:0)
此代码适用于SQL SERVER中的上述问题
create table TempTable -------Creating table
(
Person varchar(20),
[Date] date ,
Score float
)
Declare @person varchar(20),@StartDate date,@Enddate date,@Score float,@temp int = 1,@count int ; -----------Local variable declaring
select @count = count(*) from <YourTableName> ------Row count
while ( @count > 0)
begin
with CTE_Select
as
(
select row_number() over (order by Person) id, * from [dbo].[difference_table]
)
select @person = Person,@StartDate = [Start_date],@Enddate = End_date,@Score = Score from CTE_Select
where id = @temp -------------Taking first Row
Declare @diff int = datediff(dd,@StartDate,@Enddate)
while (@diff > 0 )
begin
insert into temptable (Person,[Date],Score)
select @person,@StartDate,@Score
set @StartDate = DATEADD(dd,1,@StartDate)
Set @diff = @diff - 1
end
set @temp = @temp + 1 ---------------selecting next row
set @count = @count - 1 ---------------decreasing row count
end ;
select * from TempTable; ------------Select modified table