4

次の表があると仮定します

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

ヒントをありがとう!

PS:私はDB2を使用しています

4

3 に答える 3

2

これを試して:

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フィドルデモ

于 2012-08-28T10:30:12.090 に答える
0
select 
    age_category as "category",
    sum(case when amount>0 then 1 else 0 end ) as "total claims",
    count(*) as "total people",
    sum(amount) as "amount"
from
    my_table
group by
    age_category
于 2012-08-28T10:25:32.057 に答える
0

count(DISTINCT)を使用してみてください:

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

またはこれを使用してみてください:

select t.*,
(select count(*) from

(select distinct claim_id from my_table 
   where my_table.age_category=t.category) as d
 ) as "total_claims"
from
(
select 
    age_category as "category",
    count(*) as "total people",
    sum(amount) as "amount"
from
    my_table
group by
    age_category
  ) as t
于 2012-08-28T10:27:45.517 に答える