SQL查询以跨多行显示“总列”

假设我有下表

claim_id | person_id | age_category | amount
--------------------------------------------
       1 |         1 |        adult |  10.00
       1 |         2 |        adult |  10.00
       1 |         3 |     juvenile |   8.00
       1 |         4 |        child |   5.00
       2 |         5 |        adult |  15.00
       3 |         6 |        adult |  12.00
       3 |         7 |        child |   6.00
     ...
     100 |       250 |        child |   7.00

所以有几个人可能属于同一个主张.
我已经设法实现的是这样一个结果表:

category | total people |     amount
------------------------------------
adult    |          150 | 300'000.00
juvenile |           20 |  40'000.00
child    |           80 | 160'000.00

使用以下查询:

select 
    age_category as "category"
    count(*) as "total people",
    sum(amount) as "amount"
from
    my_table
group by
    age_category

有没有办法计算索赔数量并将其显示在同一结果表中?例如.就像是:

category | total claims | total people |     amount
---------------------------------------|-----------
adult    |          100 |          150 | 300'000.00
juvenile |              |           20 |  40'000.00
child    |              |           80 | 160'000.00

谢谢你的任何提示!

P.S.:我正在使用DB2

最佳答案 试试这个:

select 
    age_category as "category",
    COUNT(distinct claim_id ) as "total_claims", --  <-- add this line 
    count(*) as "total people",
    sum(amount) as "amount"

from
    my_table
group by
    age_category

编辑:

根据您的评论,使用此查询

select 
    age_category as "category",
    case when age_category='adult' then COUNT(distinct claim_id ) end 
                                                         as "total_claims" , 
    count(*) as "total people",
    sum(amount) as "amount"

from
    my_table
group by
    age_category  

SQL Fiddle Demo

点赞