IF 列有重复值 THEN 选择下一个

IF column has a duplicated value THEN choose the next one

感谢您的关注。

如何在 Bigquery 中编写 IF 语句 SQL,总结一下单位数(如果 QUARTER 列具有相同的季度,则选择带有 TYPE ACTL、OTLK、ETC 的单位数) . TYPE CWV 是历史数据,所以可以有重复的季度,但如果有 TYPE ACTL、OTLK 等单位与 CWV 中的季度相同,那么我希望 SQL 选择 UNITS with TYPE ACTL、OTLK, CWV 等。

注意:此 sql 将用于 Tableau,我的 XYZ 单位总数应为 977071(不包括 CWV / FY20-Q4 / 104955)

Row TMC_BC TYPE PROGRAM QUARTER UNITS
1 TMC ACTL XYZ FY20-Q2 0
2 TMC OTLK XYZ FY20-Q3 6500
3 TMC CWV XYZ FY20-Q4 104955
4 TMC ACTL XYZ FY20-Q4 191300
5 TMC CWV XYZ FY21-Q1 182448
6 TMC_BC CWV XYZ FY21-Q2 91346
7 TMC CWV XYZ FY21-Q2 158126
8 TMC_BC CWV XYZ FY21-Q1 62500
9 TMC CWV XYZ FY21-Q1 157287
10 TMC_BC CWV XYZ FY21-Q1 62500
11 TMC CWV XYZ FY21-Q1 31410
12 TMC_BC CWV XYZ FY21-Q1 33654

我现在的 SQL:

SELECT
case when tmc <= 0 then 'TMC_BC'
      else 'TMC'
      end as TMC_BC,
TYPE,
PROGRAM,
QUARTER,
sum(ca) as UNITS,
from xx_REPORTS
where PROGRAM like 'XYZ'
and TYPE <> 'PDP' and TYPE <> 'POR'
and GEO = 'NA'
group by 1,2,3,4
order by 4 asc

嗯。 . .如果我理解正确,只有当 quarter/PROGRAM/tmc_bc 组合没有其他类型时,您才需要 'CWV' 。您可以使用 window 函数进行此过滤:

select r.*
from (select r.*,
             count(*) over (partition by quarter, program, tmc_bc) as q_cnt,
             countif(type = 'CWV') over (partition by quarter, program, tmc_bc) as q_cnt_cwv
      from xx_REPORTS r
     ) r
where (q_cnt = q_cnt_cwv) or (type <> 'CWV');

其实如果逻辑是正确的,那么你要的是非CMV行,如果有的话,否则就是所有行。一个更简单的表达式是:

select r.*
from (select r.*,
             countif(type <> 'CWV') over (partition by quarter, program, tmc_bc) as q_cnt_noncwv
      from xx_REPORTS r
     ) r
where (q_cnt_noncwv > 0 and type <> 'CWV') or q.cnt_noncwv = 0;