【问题标题】:Filtration on columns created using CASE Postgresql过滤使用 CASE Postgresql 创建的列
【发布时间】:2021-10-07 20:05:09
【问题描述】:

我有一张下表:

id int
user_id int
created_at datetime
status varchar
type varchar

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

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

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 创建列的信息,发现人们确实将列名用双引号括起来(我附上了示例截图)。 那为什么我的查询不能这样工作。

【问题讨论】:

    标签: sql postgresql case having-clause


    【解决方案1】:

    您应该在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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        为什么不这样简单

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

        【讨论】:

          猜你喜欢
          • 2018-03-22
          • 2021-06-27
          • 2021-04-02
          • 2021-11-29
          • 1970-01-01
          • 2019-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多