MS Access 2010:根据1个价格记录创建多周记录

时间:2014-09-21 21:07:16

标签: sql access-vba ms-access-2010

您能否帮我解决以下问题: 我有table1有5个字段:ProductID,price,startWeek,endWeek,numWeeks;

xx ProdID xx price xx startWeek xx endWeek xx NumWeeks
   Prod1       $15       1           3           3
   Prod2       $20       2           4           3 

我需要创建另一个table2来按周一按产品ID记录价格,因此每个产品都会有每周的记录数,如下所示:

Prod1 week1 $15,
Prod1 week2 $15
Prod1 week3 $15
Prod2 week2 $20
Prod2 week3 $20
Prod3 week4 $20

非常感谢提前

1 个答案:

答案 0 :(得分:0)

TEST SQLFiddle

首先,我将创建一个表数周。它通常被称为计数表或数字表。

你可以通过VBA创建一个,但我想简单地保持(很长,但很简单)

您必须只运行一次此代码。

create table weeks(weekNumber int, weekName varchar(10))
insert into weeks 
select 1, 'week1'
union all
select 2, 'week2'
union all
select 3, 'week3'
union all
select 4, 'week4'
union all
select 5, 'week5'
union all
select 6, 'week6'
union all
select 7, 'week7'
union all
select 8, 'week8'
union all
select 9, 'week9'
union all
select 10, 'week10'
union all
select 11, 'week11'
union all
select 12, 'week12'
union all
select 13, 'week13'
union all
select 14, 'week14'
union all
select 15, 'week15'
union all
select 16, 'week16'
union all
select 17, 'week17'
union all
select 18, 'week18'
union all
select 19, 'week19'
union all
select 20, 'week20'
union all
select 21, 'week21'
union all
select 22, 'week22'
union all
select 23, 'week23'
union all
select 24, 'week24'
union all
select 25, 'week25'
union all
select 26, 'week26'
union all
select 27, 'week27'
union all
select 28, 'week28'
union all
select 29, 'week29'
union all
select 30, 'week30'
union all
select 31, 'week31'
union all
select 32, 'week32'
union all
select 33, 'week33'
union all
select 34, 'week34'
union all
select 35, 'week35'
union all
select 36, 'week36'
union all
select 37, 'week37'
union all
select 38, 'week38'
union all
select 39, 'week39'
union all
select 40, 'week40'
union all
select 41, 'week41'
union all
select 42, 'week42'
union all
select 43, 'week43'
union all
select 44, 'week44'
union all
select 45, 'week45'
union all
select 46, 'week46'
union all
select 47, 'week47'
union all
select 48, 'week48'
union all
select 49, 'week49'
union all
select 50, 'week50'
union all
select 51, 'week51'
union all
select 52, 'week52'
union all
select 53, 'week53'
union all
select 54, 'week54'
union all
select 55, 'week55'

然后解决方案很简单:

1-create table2,只运行一次

create table table2(ProductID varchar(10), weekName varchar(10), price int)

做好工作

    insert into table2
    select a.ProductID, w.weekName, a.price 
    from table1 a inner join weeks w 
    on a.startWeek<=w.weekNumber and a.endWeek>=w.weekNumber

获得结果

select * from table2

结果:

ProductID   weekName    price
Prod1       week1       15
Prod1       week2       15
Prod1       week3       15
Prod2       week2       20
Prod2       week3       20
Prod2       week4       20

TEST SQLFiddle