0

oracle10g に次のテーブルがあります。

   state     gender   avg_sal   status
    NC           M      5200     Single 
    OH           F      3800     Married
    AR           M      8800     Married
    AR           F      6200     Single
    TN           M      4200     Single
    NC           F      4500     Single

いくつかの条件に基づいて、次のレポートを作成しようとしています。レポートは次のようになります。以下のクエリを試しましたが、count(*) が期待どおりに機能しません

state     gender no.of males no.of females   avg_sal_men      avg_sal_women
 NC           M       10            0           5200                 0
 OH           F        0            5           0                  3800
 AR           M        16           0           8800                  0
 AR           F        0            12          0                  6200
 TN           M        22            0          4200                  0
 NC           F        0             8          0                   4500

次のクエリを試しましたが、男性の数と女性の数に基づいて数えることができません..

    select State, "NO_OF MALES", "$AVG_sal", "NO_OF_FEMALES", "$AVG_SAL_FEMALE"
    from(
    select State,
    to_char(SUM((CASE WHEN gender = 'M' THEN average_price ELSE 0 END)),'$999,999,999') as "$Avg_sal_men,
     to_char(SUM((CASE WHEN gender = 'F' THEN average_price ELSE 0 END)), '$999,999,999') as "$Avg_sal_women,
     (select count (*) from table where gender='M')"NO_OF MALES",
    (select count (*) from table where gender='F')"NO_OF_FEMALES"
     from table group by State order by state);
4

3 に答える 3

1

式として使用できますcase(すでに知っている...)。また、サブクエリは不要です。

select State
     , sum(case gender when 'M' then 1 else 0 end) as "no.of males"
     , sum(case gender when 'F' then 1 else 0 end) as "no.of females"
     , to_char(
           SUM(
               (
                   CASE
                   WHEN gender = 'M' THEN average_price
                   ELSE 0
                   END
               )
           )
         , '$999,999,999'
       ) as "Avg_sal_men",
       to_char(SUM((CASE WHEN gender = 'F' THEN average_price ELSE 0 END))
              ,'$999,999,999'
     ) as "Avg_sal_women"
from table
group by State;
于 2013-05-14T10:40:23.793 に答える
0

select count (*) from table where gender='M'テーブル全体の男性の総数を常にカウント するこのサブクエリでコンティングしています....そして、女性をカウントするために同じことをしています...だから、このように試すことができます...

select State, "NO_OF MALES", "$AVG_sal", "NO_OF_FEMALES", "$AVG_SAL_FEMALE"
        from(
        select State,
        to_char(SUM((CASE WHEN gender = 'M' THEN average_price ELSE 0 END)),'$999,999,999') as "$Avg_sal_men",
         to_char(SUM((CASE WHEN gender = 'F' THEN average_price ELSE 0 END)), '$999,999,999') as "$Avg_sal_women,
        Sum(Case when gender='M' then 1 else 0 end) "NO_OF MALES",
         Sum(Case when gender='F' then 1 else 0 end) "NO_OF_FEMALES"
         from table group by State order by state);
于 2013-05-14T10:35:15.280 に答える