条件 SQL 逻辑

Conditional SQL logic

我有一个简单的table登记选民的投票频率

create table public.campaign_202206 (
    registrant_id INTEGER not null references votecal.voter_registration (registrant_id),
    voting_frequency smallint
);

我想在此 table 中插入值,其中包含选民在过去四次选举中参与的选举计数:

insert into campaign_202206 (
  select registrant_id, count(*)
  from votecal.voter_participation_history
  where election_date in ('2021-09-14', '2020-11-03', '2020-03-03', '2018-11-06')
  group by registrant_id
);

但是,如果计数是 1,那么我想查看 '2018-06-05' 前五次选举的参与情况,如果没有参与那次选举,我想存储voting_frequency 作为 0 而不是 1.

insert into campaign_202206 (
  select
    registrant_id,
    case
      when count(*) = 1 then --- what goes here?
      else count(*)
    end as voting_frequency
  from votecal.voter_participation_history
  where election_date in ('2021-09-14', '2020-11-03', '2020-03-03', '2018-11-06')
  group by registrant_id
);

在这种情况下,什么时候会得到这个特殊情况的值?

使用相关子查询如下:

insert into campaign_202206 (
  select
    registrant_id,
    case when count(*) = 1 then
            (
                select count(*)
                  from votecal.voter_participation_history sqvph
                 where sqvph.election_date = '2018-06-05'
                   and sqvph.registrant_id = vph.registrant_id
            )
        else count(*)
    end as voting_frequency
  from votecal.voter_participation_history vph
  where election_date in ('2021-09-14', '2020-11-03', '2020-03-03', '2018-11-06')
  group by registrant_id
);

查询中的结果集提供程序需要别名才能正常工作。

用户嵌套案例:

insert into campaign_202206 (
 select
  registrant_id, 
     case
     when count(*) = 1 then 
           case
              when (select count(*) from voter_participation_history
                     where election_date in ('2018-06-05') and registrant_id 
                    = v1.registrant_id) > 0  
              then 1
              else 0
           end 
  else count(*)
  end as voting_frequency from voter_participation_history v1 where 
   election_date in ('2021-09-14', '2020-11-03', '2020-03-03', '2018-11-06') 
   group by v1.registrant_id);