如何在IBM DB2中获得此结果?

时间:2017-08-10 12:50:41

标签: sql db2

例如,我有两个模式: SCHEMA_1 SCHEMA_2 。在 SHEMA_1 中,我有一个名为 TABLE 的表。该表包括两个字段:FIELD_1,FIELD_2。在FIELD_1的TABLE中,我有一些字母:A,B,C。FIELD_2有表格' SCHEMA 2的名称:TABLE_10,TABLE_20,TABLE_30。

SCHEMA_2 包含三个表: TABLE_10 TABLE_20 TABLE_30 以及一些数字。 enter image description here

我必须编写查询以获取SCHEMA_2中每个表的最大数量。我怎样才能得到这个结果> enter image description here

1 个答案:

答案 0 :(得分:0)

试试这个:

create table schema1.tableA
  (field_1    char(1),
   field_2    varchar(10)); 
insert into schema1.tableA
  values ('A','table_10'),
         ('B','table_20'),
         ('C','table_30');  

create table schema2.table_10
  (field_1    dec(5,0));
insert into schema2.table_10
  values (20), (30), (40);
create table schema2.table_20
  (field_1    dec(5,0));
insert into schema2.table_20
  values (6), (9), (12);
create table schema2.table_30
  (field_1    dec(5,0));
insert into schema2.table_30
  values (10), (15), (20);

with tmp (table_name, field_1) as (
  select 'table_10', max(field_1) from schema2.table_10
  union all
  select 'table_20', max(field_1) from schema2.table_20
  union all
  select 'table_30', max(field_1) from schema2.table_30)
select a.field_1, b.field_1
  from schema1.tableA a
    join tmp b on b.table_name = a.field_2;

如果您有太多的表来完成上述工作,您可以使用这样的用户定义函数:

create or replace function MaxNbr
    (p_TableName      varchar(128),
     p_TableSchema    varchar(128))
  Returns dec(5,0)
  language sql
  not deterministic
  no external action
  reads sql data
  returns null on null input
  not fenced
begin
  declare l_stmt     varchar(1024);
  declare l_table    varchar(128);
  declare l_schema   varchar(128);
  declare l_result   dec(5,0);

  set l_table = replace(upper(p_TableName),'"','');
  set l_schema = replace(upper(p_TableSchema),'"',''); 
  set l_stmt = 'values (select max(field_1) from "' || l_schema || '"."' ||
               trim(l_table) || '") into ?';

  prepare S1 from l_stmt;
  allocate sql descriptor 'D1';
  describe S1 using sql descriptor 'D1';
  execute S1 into sql descriptor 'D1';
  get sql descriptor 'D1' value 1 l_result = data;
  deallocate sql descriptor 'D1';

  return l_result;
end;

这是必要的,因为您不能将变量用于表名或模式名称等标识符。

要使用用户定义的功能,您可以执行以下操作:

set schema schema1;
set path = udf_schema;

select field_1, MaxNbr(field_2, 'schema2') as field_2
  from tableA;