SQL子查询:没有Cats的状态

时间:2016-11-13 19:34:26

标签: sql oracle oracle-sqldeveloper

我有一张名为A10的桌子。我想创建一个名为A10T1的视图,它将显示没有cat值为Y的人的每个状态的状态缩写。我需要使用子查询但不会输出。

我目前的代码是:

CREATE VIEW A10T1 AS
SELECT STATE
FROM A10
WHERE STATE IS NOT NULL AND ID IN
 (SELECT ID
  FROM A10
  GROUP BY ID
  HAVING COUNT(ID) =
   (SELECT MIN(CATLOVERS)
    FROM (SELECT COUNT(ID) AS CATLOVERS
          FROM A10
          WHERE CAT = 'Y'
          GROUP BY STATE)))
ORDER BY STATE;

2 个答案:

答案 0 :(得分:2)

可惜有人刚刚给你一份作业答案,你可以通过这种方式练习复制/粘贴,但学习不多。

为什么您的查询失败?

自行运行此查询:

SELECT COUNT(ID) AS CATLOVERS
      FROM A10
      WHERE CATLOVERS = 'Y'
      GROUP BY STATE

从子查询得到的是一列正整数,除非没有状态有catlovers ='Y',如果发生这种情况,子查询将返回NULL。

现在考虑

SELECT MIN(CATLOVERS)
FROM (SELECT COUNT(ID) AS CATLOVERS
      FROM A10
      WHERE CATLOVERS = 'Y'
      GROUP BY STATE)x

因此,一系列正整数的MIN()可能是1,并且此子查询将返回单行1,除非第一个子查询返回NULL,这也会导致NULL。

因此,如果较早的子查询为NULL,则下一个子查询将仅列出其中count(ID)=最小或没有行的ID

SELECT ID
  FROM A10
  GROUP BY ID
  HAVING COUNT(ID) =
   (SELECT MIN(CATLOVERS)
    FROM (SELECT COUNT(ID) AS CATLOVERS
          FROM A10
          WHERE CATLOVERS = 'Y'
          GROUP BY STATE)x)

尝试独立运行子查询以研究发生的情况。

请参阅:http://data.stackexchange.com/stackoverflow/query/577188

答案 1 :(得分:-1)

首先你需要创建视图:

CREATE OR replace VIEW a10t1 
AS 
  SELECT state 
  FROM   a10 
  WHERE  state IS NOT NULL 
         AND id IN (SELECT id 
                    FROM   a10 
                    GROUP  BY id 
                    HAVING Count(id) = (SELECT Min(catlovers) 
                                        FROM   (SELECT Count(id) AS CATLOVERS 
                                                FROM   a10 
                                                WHERE  cat = 'Y' 
                                                GROUP  BY state))) 
  ORDER  BY state; 

然后你可以从这个视图中选择:

select * from a10t1