[英]Filtration on columns created using CASE Postgresql
I have a table below:我有一个下表:
id int
user_id int
created_at datetime
status varchar
type varchar
and I am trying to answer the question "Write a query that returns the user ID of all users that have created at least one 'Refinance' submission and at least one 'InSchool' submission."我正在尝试回答问题“编写一个查询,返回所有创建了至少一个'Refinance'提交和至少一个'InSchool'提交的用户的用户ID。”
I figured out how this will be done:我想出了如何做到这一点:
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
When I run only the inner query, everything is fine.当我只运行内部查询时,一切都很好。 I am getting 3 columns but when I run the whole query it says column Refinancecount doesn't found.我得到 3 列,但是当我运行整个查询时,它说找不到列 Refinancecount。 I looked on internet and found when I am aliasing my case columns then I should't wrap them in double quotes and the query worked fine using this suggestion.我在互联网上查看,发现当我为我的案例列起别名时,我不应该将它们用双引号括起来,并且使用这个建议查询工作正常。 But I read more about creating columns using CASE in postgre, and found people do wrap column names in double quotes (I have attached an example screenshot)但我阅读了更多关于在 postgre 中使用 CASE 创建列的信息,发现人们确实将列名用双引号括起来(我附上了一个示例截图) . . Then why my query doesn't work this way.那么为什么我的查询不能以这种方式工作。
You should quote those fields in the where
clause.您应该在where
子句中引用这些字段。 Try:尝试:
where "Refinancecount" >= 1 and "Inschoolcount" >= 1
By the way, you can write this query without inner query, by using having
clause:顺便说一句,您可以使用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
Yea it's said column Refinancecount doesn't found because you need to use quote where a."Refinancecount">=1 and a."Inschoolcount">=1
.是的,据说没有找到 Refinancecount 列,因为您需要使用 quote where a."Refinancecount">=1 and a."Inschoolcount">=1
。 If you name your column as "Inschoolcount" you need to refer to it with the "" otherwise a.Refinancecount will be converted to a.refinancecount如果您将列命名为“Inschoolcount”,则需要用“”引用它,否则 a.Refinancecount 将转换为 a.refinancecount
Why not make it simple like this为什么不让它像这样简单
select
user_id
from
loans
group by user_id having
sum(
case
when type in ('Refinance',
'InSchool') then 1 else 0 end >=2)
SELECT DISTINCT l1.user_id SELECT DISTINCT l1.user_id
from
loans l1
join
loans l2
where在哪里
l1.type = 'Refinance'
and和
l2.type = 'InSchool'
; ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.