合并两个sqldf语句

时间:2017-11-05 07:00:09

标签: sql sqlite subquery sqldf

我现在一整天都在努力。有人可以帮我合并下面的查询。我在下面得到了理想的结果,但我知道它应该在一个中完成。

Maybe'

1 个答案:

答案 0 :(得分:2)

答案取决于接收SQL的数据库,没有with你必须重复“moo”查询

  SELECT id, idcount  
  FROM (
       SELECT id, count(id) AS idcount 
       FROM MyData WHERE id IS NOT NULL 
       GROUP BY id 
       ) moo 
  WHERE idcount = (
    SELECT min(idcount) 
    FROM (
       SELECT id, count(id) AS idcount 
       FROM MyData WHERE id IS NOT NULL 
       GROUP BY id 
       ) 
  OR idcount = (
    SELECT max(idcount) 
    FROM (
       SELECT id, count(id) AS idcount 
       FROM MyData WHERE id IS NOT NULL 
       GROUP BY id 
       ) 

你可能最好在代码中执行此操作而不是在SQL

中执行此操作

如果dbms确实支持WITH,那么:

  WITH moo AS (  
  SELECT id, idcount  
  FROM (
       SELECT id, count(id) AS idcount 
       FROM MyData WHERE id IS NOT NULL 
       GROUP BY id 
       ) 
    )
  SELECT id, idcount  
  FROM moo
  WHERE idcount = (
    SELECT min(idcount) 
    FROM moo)
  OR idcount = (
    SELECT max(idcount) 
    FROM moo)