对使用 CASE Postgresql 创建的列进行过滤

Filtration on columns created using CASE Postgresql

我下面有一个table:

id int
user_id int
created_at datetime
status varchar
type varchar

我正在尝试回答“编写一个查询,returns 已创建至少一个‘Refinance’提交和至少一个‘InSchool’提交的所有用户的用户 ID。”。 =13=]

我想出了如何做到这一点:

select
    a.user_id
from
    (select
        user_id,
        sum(
            case
                when type='Refinance' then 1 else 0 end) as "Refinancecount",
        sum(
            case
                when type='InSchool' then 1 else 0 end) as "Inschoolcount"
    from
        loans
    group by 1) as a
where a.Refinancecount>=1 and a.Inschoolcount>=1

当我运行只有内部查询时,一切都很好。我得到 3 列,但是当我 运行 整个查询时,它说找不到列 Refinancecount。 我查看了互联网,发现当我为我的案例列设置别名时,我不应该将它们用双引号引起来,并且使用此建议查询工作正常。 但是我阅读了更多有关在 postgre 中使用 CASE 创建列的信息,发现人们确实将列名用双引号引起来(我附上了示例屏幕截图)。 那么为什么我的查询不能这样工作。

您应该在 where 子句中引用这些字段。尝试:

where "Refinancecount" >= 1 and "Inschoolcount" >= 1

顺便说一句,您可以使用 having 子句编写此查询而无需内部查询:

select
        user_id
from
        loans
group by 1
having sum(case when type='Refinance' then 1 else 0 end) >=1 and sum(case when type='InSchool' then 1 else 0 end) >= 1

是的,据说找不到列 Refinancecount,因为您需要使用引号 where a."Refinancecount">=1 and a."Inschoolcount">=1。如果您将列命名为“Inschoolcount”,则需要使用“”引用它,否则 a.Refinancecount 将转换为 a.refinancecount

为什么不这样简单

 select
    user_id
     from
    loans
   group by user_id having
   sum(
        case
            when type in ('Refinance', 
             'InSchool') then 1 else 0 end >=2)