我想从日历和日期中填写表格 dim_Date(idDate,date,year,month,trimester,weekNumber,week,day) 格式为“年/月/日 hh:mm 你能帮帮我吗
问问题
311 次
1 回答
0
我在这里做了一些假设,因为你没有说日期格式的格式是什么(我假设是一个 varchar)并且你没有指定周数和周是什么......所以我假设一年中的一周和一个月的一周:
-->set up data for example
create table dummy_date_table
(dummy_date varchar(50))
go
-->insert dummy data(assuming you have these somewhere as text?)
insert into
dummy_date_table (dummy_date) values
('2010/11/01 01:22'),
('2013/06/02 03:16'),
('2012/07/03 05:32'),
('2011/01/04 06:04')
go
-->create date dimension based on your logic
create table dim_Date(
idDate int, -->pk
date datetime, -->full date
year int,-->year of date
month int,-->month of date
trimester int,-->trimester 1,2,3
weekNumber int,-->week number in year
week int, -->week number in month
day int --.day part of date
)
go
-->used for primary key|date|year|month|trimester|weeknumber|week|day
declare @i int=1, @date datetime, @year int, @month int, @trimester int, @weeknumber int, @week int, @day int
-->cursor to insert our data
declare date_inserter cursor for
select
convert(datetime,left(dummy_date,10)),
datepart(year,convert(datetime,left(dummy_date,10))),
datepart(month,convert(datetime,left(dummy_date,10))),
case
when datepart(month,convert(datetime,left(dummy_date,10))) <5 then 1
when datepart(month,convert(datetime,left(dummy_date,10))) >4 and datepart(month,convert(datetime,left(dummy_date,10))) <9 then 2
else 3
end,
datepart(ISO_WEEK,convert(datetime,left(dummy_date,10))),
DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, convert(datetime,left(dummy_date,10))), 0), convert(datetime,left(dummy_date,10))) +1 ,
datepart(day,convert(datetime,left(dummy_date,10)))
from
dummy_date_table;
open date_inserter;
fetch next from date_inserter into
@date,
@year,
@month,
@trimester,
@weeknumber,
@week,
@day
WHILE @@FETCH_STATUS = 0
BEGIN
insert into dim_Date
select @i, @date, @year, @month, @trimester, @weeknumber, @week, @day
set @i+=1;
fetch next from date_inserter into
@date,
@year,
@month,
@trimester,
@weeknumber,
@week,
@day
END
-->Cleanup
CLOSE date_inserter
DEALLOCATE date_inserter
go
-->Look at data
select * from dim_Date
结果:
idDate date year month trimester weekNumber week day
1 2010-11-01 00:00:00.000 2010 11 3 44 1 1
2 2013-06-02 00:00:00.000 2013 6 2 22 2 2
3 2012-07-03 00:00:00.000 2012 7 2 27 1 3
4 2011-01-04 00:00:00.000 2011 1 1 1 2 4
于 2013-07-23T18:30:09.083 回答