数据库查询:如何计算多个列的最大值

时间:2012-08-27 08:53:56

标签: sql

假设我有下表

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人)和最多儿童人数(此处:2人)。 有没有办法通过单个查询实现这一目标?感谢任何提示。

5 个答案:

答案 0 :(得分:3)

使用派生表获取计数,然后选择max:

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

答案 1 :(得分:2)

使用嵌套查询:

    select max(nbr_of_adults) maxAd, max(nbr_of_children), maxCh from
    (
        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    
    )

答案 2 :(得分:2)

我不知道你的dbms是什么,但是在sybase上它可以工作:

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

答案 3 :(得分:0)

select     
person_type,     
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 ;

答案 4 :(得分:0)

如果您的SQL产品支持窗口聚合函数,您可以尝试这样的事情:

SELECT DISTINCT
  MAX(COUNT(CASE person_type WHEN 'adult' THEN 1 END)) OVER () AS max_adult_count,
  MAX(COUNT(CASE person_type WHEN 'child' THEN 1 END)) OVER () AS max_child_count
FROM claim_table
GROUP BY claim_date

我还用条件COUNT替换了你的条件SUM,这在我看来更清晰,更简洁。