使用SELECT UNION并从一个表返回两列的输出

时间:2012-11-27 20:29:58

标签: sql oracle select union

我正在创建一个查询,计算表格中男性和女性角色的数量。我目前的陈述是这样的:

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 个答案:

答案 0 :(得分: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')

答案 1 :(得分:8)

另一种方式(没有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  ;

答案 2 :(得分: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 

答案 3 :(得分:5)

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

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

请参阅SQL Fiddle with Demo

结果将是:

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

或者您可以使用CROSS 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