2

我需要在选择中显示两组之间最常见的值,并且它必须伴随一条消息,所以请耐心等待。我正在使用 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 的变种人多于类型 1,它会显示英雄,然后当类型 1 的数量多于类型 0 时,它会显示恶棍,但是当它们并列时,它不会显示任何数据,这不会为我工作:(我需要它说“都不”,所以任何帮助都将受到广泛赞赏。

4

2 回答 2

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
于 2012-09-23T07:41:36.617 回答
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

于 2012-09-23T08:29:32.817 回答