根据第三列的值,尝试返回两列之一的总和(分组依据)

时间:2019-06-18 14:08:30

标签: sql select db2

我在DB2(IBM Spectrum Protect)中有一个表,我试图提取一个报表,如果该报表是常规备份,则该报表在ENTITY中具有服务器名称,但是如果是VM备份,则将该服务器名称置于SUB_ENTITY中。我希望能够获得一个完整的列表,将两者的结果结合起来,然后计算X天的总备份量。在执行此操作时,我需要能够从VM节点server_name中分解出客户代码。我当前的解决方案是使用两个不同的选择提取数据并手动组合数据。

我尝试了一个案例的选择,但分组依据返回错误。

select -
   varchar(ACTIVITY_DETAILS,20) as ACTIVITY_DETAILS, -
  case -
   when ACTIVITY_DETAILS='VMware' -
    then -
     varchar(sub_entity,47) -
    else -
     VARCHAR(ENTITY,47) -
   end as CUSTOMER_ID, -
sum(bytes)/1024/1024/1024 as TOTAL_GB -
from summary_extended -
 where -
 activity in ('BACKUP') -
 and -
 start_time>=(current_timestamp - 30 days)
group by CUSTOMER_ID

我需要按案件结果分组,但不能按CUSTOMER_ID分组。我得到以下内容

  

ANR0162W补充数据库诊断信息:-1:42S22:-206([IBM] [CLI驱动程序] [DB2 / AIX64] SQL0206N“ CUSTOMER_ID”在使用上下文中无效。SQLSTATE = 42703   )。

1 个答案:

答案 0 :(得分:0)

您可以使用子查询来定义别名:

select varchar(ACTIVITY_DETAILS, 20) as ACTIVITY_DETAILS, 
       customer_id,
       sum(bytes) / (1024*1024*1024) as TOTAL_GB
from (select se.*,
             (case when ACTIVITY_DETAILS = 'VMware'
                   then varchar(sub_entity, 47)
                   else VARCHAR(ENTITY, 47)
              end) as CUSTOMER_ID
      from summary_extended se
     ) se
where activity in ('BACKUP') and
      start_time >= (current_timestamp - 30 days)
group by varchar(ACTIVITY_DETAILS, 20), 
         customer_id;