4

我正在创建一个查询表中男性和女性演员的数量。我目前的陈述是这样的:

Select COUNT(ActorGender) “Male Actors” 
from (tblActor ta WHERE ta.ActorGender in(‘m’)
UNION
Select COUNT(ActorGender) “Female Actors” 
from tblActor ta 
WHERE ta.ActorGender in(‘f’);

输出最终是:

Male Actors
-----------
          7
         21

我希望输出看起来像:

Male Actors   Female Actors
-----------   -------------
          7              21

我正在寻找一种不使用 CASE WHEN 或 THEN 子句的替代方法。

提前感谢您一如既往的帮助。

4

4 回答 4

9

另一种方式(不CASE表达):

SELECT 
  ( SELECT COUNT(*)
    FROM tblActor 
    WHERE ActorGender = 'm' 
  ) AS MaleActors
, ( SELECT COUNT(*)
    FROM tblActor 
    WHERE ActorGender = 'f' 
  ) AS FemaleActors
FROM 
    dual ;

以及更多的CROSS加入解决方案:

SELECT m.MaleActors, f.FemaleActors
FROM 
  ( SELECT COUNT(*) AS MaleActors
    FROM tblActor 
    WHERE ActorGender = 'm' 
  ) m
  CROSS JOIN
  ( SELECT COUNT(*) AS FemaleActors
    FROM tblActor 
    WHERE ActorGender = 'f' 
  ) f  ;
于 2012-11-27T20:53:20.133 回答
8

这会做:

SELECT  COUNT(CASE WHEN ActorGender = 'm' THEN 1 ELSE NULL END) MaleActors,
        COUNT(CASE WHEN ActorGender = 'f' THEN 1 ELSE NULL END) FemaleActors
FROM tblActor 
WHERE ActorGender IN ('m','f')
于 2012-11-27T20:32:43.490 回答
7

另一种不使用案例的方法:

select sum(males) as "Male Actors", sum(females) as "Female Actors" 
from 
(select count(actorGender) as Males, 0 as Females
from tblActor 
where actorGender = 'm'
union all
select 0 as males, count(actorGender) as Females
from tblActor
where actorGender = 'f')

应该导致

Male Actors    Female Actors
-----------    -------------
7              21 
于 2012-11-27T20:59:21.113 回答
5

如果您使用的是 Oracle 11g+,那么您可以使用PIVOT

select *
from
(
  select actorgender
  from tblActor
) src
pivot
(
  count(actorgender)
  for actorgender in ('m' MaleActors, 'f' FemaleActors)
) piv

请参阅带有演示的 SQL Fiddle

结果将是:

| MALEACTORS | FEMALEACTORS |
-----------------------------
|          4 |            5 |

或者您可以使用 aCROSS JOIN来获得相同的结果:

select m.MaleActors, f.FemaleActors
from 
(
  select count(ActorGender) MaleActors, 'm' Gender
  from tblActor
  where ActorGender = 'm'
) m
cross join
(
  select count(ActorGender) FemaleActors, 'f' Gender
  from tblActor
  where ActorGender = 'f'
) f
于 2012-11-27T21:02:23.470 回答