SQL视图返回有效产品列表

时间:2017-06-12 10:25:39

标签: sql db2 ibm-midrange db2-400

请协助创建SQL视图。

在DB2 For i V7R2上

情况:

我公司的部门可以出售产品清单, 直到它们被新产品取代。在新产品生效的当天,该部门可以销售这两种产品。 在COB,旧产品不再被允许出售,需要退货。

必需:

用于返回特定日期“允许”产品列表的SQL查询。

查询需要返回:

“绿梯”和“红梯”`效果=当前时间

示例数据集:

drop table QTEMP/Product_EffectiveDate_TestTable;

create table  QTEMP/Product_EffectiveDate_TestTable (
    Dept    varchar(50) not null,
    EffDat  date        not null,
    PrdCde  varchar(50) not null);

insert into  QTEMP/Product_EffectiveDate_TestTable
    ( Dept, EffDat, PrdCde)
 values
    ('Department A', CURRENT_DATE + 10 DAY  , 'Blue-Ladder'),
    ('Department A', CURRENT_DATE           , 'Green-Ladder'),
    ('Department A', CURRENT_DATE - 10 DAY  , 'Red-Ladder'),
    ('Department A', CURRENT_DATE - 20 DAY  , 'Yellow-Ladder') ;

2 个答案:

答案 0 :(得分:2)

我对每个部门的单个产品的回答是:

select * 
  from qtemp.Product_EffectiveDate_TestTable a
  where effdat = (select max(effdat) 
                  from qtemp.Product_EffectiveDate_TestTable
                  where effdat < current_date
                    and dept = a.dept)
     or effdat = current_date

如果您只对当前日期的产品感兴趣,可以将其转换为视图。但是,如果您希望能够在任何给定日期查询它,则必须创建一个表函数。

视图看起来像这样:

create view Products_By_Department as
select * 
  from qtemp.Product_EffectiveDate_TestTable a
  where effdat = (select max(effdat) 
                  from qtemp.Product_EffectiveDate_TestTable
                  where effdat < current_date
                    and dept = a.dept)
     or effdat = current_date;

UTF可能如下所示:

create or replace function xxxxxx.UTF_ProductsByDepartment
  (
    p_date Date
  )
  returns table
  (
    Dept    Varchar(50),
    EffDat  Date,
    PrdCde  Varchar(50),
  )
  language sql
  reads sql data
  no external action
  not deterministic
  disallow parallel
  return
    select dept, effdat, prdcde 
      from qtemp.Product_EffectiveDate_TestTable a
      where effdat = (select max(effdat) 
                      from qtemp.Product_EffectiveDate_TestTable
                      where effdat < p_date
                        and dept = a.dept)
         or effdat = p_date;

您可以像这样使用UTF:

select * from table(xxxxxx.utf_ProductsByDepartment(date('2017-06-13'))) a

请注意,您无法在QTEMP中添加函数,因此您必须将xxxxxx替换为适当的库,或者您可以将其保留为不合格,并以其他方式设置默认架构。

答案 1 :(得分:1)

如果可能,我会通过更改您的数据设计来解决此问题。最好在每一行上都有一个开始日期和结束日期。原因:

  • 这样可以简化查询。
  • 这是一个更清晰,更易于理解的设计。
  • 它更灵活,允许将来更改您的业务需求。“嘿,实际上我们仍然需要销售这个旧版本的产品”是一种有害的要求,有一种方式稍后弹出,理想情况下,您可以在不重写应用程序代码的情况下处理此问题。

如果您无法更改数据设计,我会使用子查询来创建结束日期:

with start_end_dates as (
    select Dept,
           EffDat as start_date,
           lead (EffDat) over (partition by Dept order by EffDat) as   end_date,
           ProdCd
       from table
)
select * from start_end_dates where
    current date between start_date and coalesce(end_date,'9999-12-31');

这假定生效日期是指特定部门内的行。如果不是这样,请根据需要更改分区子句。