gpt4 book ai didi

sql - 数据库查询 : How to count maximum for several columns

转载 作者:行者123 更新时间:2023-12-04 14:33:02 25 4
gpt4 key购买 nike

假设我有下表

claim_date   person_type
------------------------
01-01-2012 adult
05-05-2012 adult
12-12-2012 adult
12-12-2012 adult
05-05-2012 child
05-05-2012 child
12-12-2012 child

当我执行以下查询时:
select 
claim_date,
sum(case when person_type = 'adult' then 1 else 0 end) as "nbr_of_adults",
sum(case when person_type = 'child' then 1 else 0 end) as "nbr_of_children"
from my_table
group by claim_date
;

我在这里得到这个结果:
claim_date   nbr_of_adults    nbr_of_children
---------------------------------------------
01-01-2012 1 0
05-05-2012 1 2
12-12-2012 2 1

我想收到的是最大数量的成人(此处:2)和最大数量的 child (此处:2)。
有没有办法通过单个查询来实现这一目标?感谢您的任何提示。

最佳答案

使用派生表获取计数,然后选择最大值:

select max(nbr_of_adults) max_adults,
max(nbr_of_children) max_children
from
(
select
sum(case when person_type = 'adult' then 1 else 0 end) as "nbr_of_adults",
sum(case when person_type = 'child' then 1 else 0 end) as "nbr_of_children"
from my_table
group by claim_date
) a

关于sql - 数据库查询 : How to count maximum for several columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12138869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com