提问人:AlwaysJunior 提问时间:3/4/2022 更新时间:3/4/2022 访问量:1248
在 PostgreSQL 中基于条件创建新列
Creating new column based on a condition in PostgreSQL
问:
我有一张桌子,叫做人。它看起来像这样:
id,name,surname,status
1,name1,Garcia,parent
2,name2,Garcia,child
3,name3,Garcia,child
4,name4,Garcia,child
5,name5,Miller,parent
6,name6,Miller,child
7,name7,Miller,child
我想添加显示儿童计数的“childrencount”列。如果 person 是子项,则“childrencount”列的值必须为零。我的意思是
id,name,surname,status,childrencount
1,name1,Garcia,parent,3
2,name2,Garcia,child,0
3,name3,Garcia,child,0
4,name4,Garcia,child,0
5,name5,Miller,parent,2
6,name6,Miller,child,0
7,name7,Miller,child,0
我试过:
SELECT SUM(CASE WHEN status = 'child' THEN 1 ELSE 0 END) AS childrencount FROM persons GROUP BY surname;
我怎样才能写这个查询?
答:
2赞
Zakaria
3/4/2022
#1
尝试在里面做一个表达式:case
sum()
select *,
case
when status = 'child' then 0
else sum(case when status = 'child' then 1 else 0 end) over(partition by surname)
end as childrencount
from table_name;
评论
1赞
AlwaysJunior
3/5/2022
谢谢你和你的小提琴!
1赞
forpas
3/4/2022
#2
在表达式中使用窗口函数:SUM()
CASE
SELECT *,
CASE status
WHEN 'child' THEN 0
WHEN 'parent' THEN SUM((status = 'child')::int) OVER (PARTITION BY surname)
END AS childrencount
FROM persons;
评论