SQL 或运算符如何与 having 一起使用

SQL or operator how to use with having

我有一个 table,我要加入 with 运算符。我可以有 2 个组合 id table FDEL - 1 或 0 和 FDVE 1 或 0,我想做的是显示如果 - 项目有 fdve,或者项目有 fdel(和计数)但它不起作用(我可以看到所有的 fdve,或者所有的 fdel)

select
    lpad(purchase_id,10,0) as purchase_id,
   sum(has_label_fdel) as FDEL_count,
    case when  LABELS   like '%FDVE%' then 1 else 0 end as HAS_LABEL_FDVE,
    sum(has_label_fdve) as FDVE_count
 from 
    "SRC_ORACLEIWP"."PURCHASE_ANALYSIS_RULES"
    group by
    lpad(purchase_id,10,0),has_label_fdve
    
having  FDVE_count>0 -- FDEL_count>0  

您希望每个产品一个结果行,因此仅按产品分组。使用 SUM 进行计数,使用 MAX 进行聚合 yes/no.

select
  lpad(purchase_id,10,0) as padded_purchase_id,
  max(has_label_fdve) as has_labels_fdve,
  sum(has_label_fdve) as fdve_count,
  max(has_label_fdel) as has_labels_fdel,
  sum(has_label_fdel) as fdel_count
from src_oracleiwp.purchase_analysis_rules
group by padded_purchase_id
having has_labels_fdve = 1
    or has_labels_fdel = 1
order by padded_purchase_id;

我稍微更改了您的别名,因此它们与您拥有的列不同(因为这种歧义有时会导致问题)。

labels like '%FDVE%' 上的检查是不必要的,因为您已经有了 has_label_fdve 标志,它始终为 0 或 1。或者看起来是这样。如果标志可以为空,请在其上使用 COALESCE 或使用 LIKE 表达式。

如果您还没有 has_label_fdvehas_label_fdel,请改用 labels 列:

select
  lpad(purchase_id,10,0) as padded_purchase_id,
  max(case when labels like '%FDVE%' then 1 else 0 end) as has_labels_fdve,
  sum(case when labels like '%FDVE%' then 1 else 0 end) as fdve_count,
  max(case when labels like '%FDEL%' then 1 else 0 end) as has_labels_fdel,
  sum(case when labels like '%FDEL%' then 1 else 0 end) as fdel_count
from src_oracleiwp.purchase_analysis_rules
group by padded_purchase_id
having has_labels_fdve = 1
    or has_labels_fdel = 1
order by padded_purchase_id;