4

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

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)です。単一のクエリでこれを達成する方法はありますか?ヒントをありがとう。

4

5 に答える 5

3

派生テーブルを使用してカウントを取得し、最大を選択します。

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
于 2012-08-27T09:01:48.953 に答える
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    
    )
于 2012-08-27T09:02:15.760 に答える
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
于 2012-08-27T09:04:33.587 に答える
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 ;
于 2012-08-27T08:59:26.137 に答える
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

また、条件付きSUMを条件付きCOUNTに置き換えました。これは、より明確で簡潔に思えました。

于 2012-08-27T09:10:11.843 に答える