SQL 查看 return 有效产品列表

SQL View to return Listing of Effective Products

请协助创建 SQL 视图。

在 DB2 For i V7R2 上

情况:

我公司的部门可以销售产品清单, 直到他们被新产品取代。在新产品生效之日,该部门可以销售这两种产品。 在COB,旧产品不再允许销售,需要returned。

必填:

SQL 查询 return 特定日期的 "allowed" 产品列表。

查询需要return:

"Green-Ladder" 和 "Red-Ladder"`WHERE EFFDAT = CURRENT_DATE

示例数据集:

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') ;

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

  • 它使查询更简单。
  • 设计更清晰、更容易理解。
  • 它更灵活,允许将来更改您的业务需求。 "Hey, actually we need to still sell this old version of the product" 是一种有害的需求,以后可能会突然出现,理想情况下您无需重写应用程序代码即可处理此问题。

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

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');

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

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

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

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

视图看起来像这样:

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 替换为适当的库,或者您可以不限定它,并以其他方式设置默认模式。