假设我有下表
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
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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