查询最常见的值或两者都不

时间:2012-09-23 07:22:06

标签: sql oracle

我需要在选择中显示两组之间最常见的值,并且必须发送消息,所以请耐心等待。我正在使用Oracle XE,这是我到目前为止所做的:

SELECT (
    CASE type
        WHEN 0 THEN 'heroes'
        WHEN 1 THEN 'villains'
        ELSE 'neither'
    END
) AS MostFrequent
FROM (
    SELECT type
    FROM mutants
    GROUP BY type
    ORDER BY count(*) DESC
) WHERE rownum <= 1

到目前为止,如果有更多类型为0的Mutants而不是类型1,则显示Heroes,然后当类型1的类型多于类型0时,它会显示恶棍,但是当它们被绑定时,它显示没有数据,并且对我不起作用:(我需要它说'不',所以任何帮助都会受到广泛赞赏。

2 个答案:

答案 0 :(得分:3)

WITH
RECOUNTS AS
(    
  SELECT
    NVL(COUNT(CASE TYPE WHEN 0 THEN TYPE END), 0) AS HEROES,
    NVL(COUNT(CASE TYPE WHEN 1 THEN TYPE END), 0) AS VILLAINS
  FROM MUTANTS
)
SELECT
  CASE WHEN HEROES > VILLAINS THEN 'heroes'
       WHEN HEROES < VILLAINS THEN 'villains'
       ELSE 'neither'
  END AS MOSTFREQUENT
FROM RECOUNTS

答案 1 :(得分:1)

看看这个SQL Fiddle

select 
   case when heroes > villains then 'heroes'
        when heroes < villains then 'villains'
        else 'neither'
   end as MostFrequent  
from ( select 
        (select count(*) from mutants where type = 0) as heroes,
        (select count(*) from mutants where type = 1) as villains
      from dual)
;

最重要的是,如果没有两者的结果,你就无法决定“不”。要实现这一点,您需要先使用子查询进行计数。计数可以用不同的方式完成,上面的效率可能比GuiGi的建议效率低一点,这也是有效的,见SQL Fiddle