合并两个 sqldf 语句
combining two sqldf statements
我已经试了一整天了。有人可以帮我结合以下查询。我在下面得到了想要的结果,但我知道应该一次完成。
moo<-sqldf('SELECT id, count(id) AS idcount
FROM MyData WHERE id IS not null
GROUP BY id')
sqldf("SELECT id, idcount FROM moo
WHERE idcount = (SELECT min(idcount) FROM moo)")
答案将取决于接收 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)
我已经试了一整天了。有人可以帮我结合以下查询。我在下面得到了想要的结果,但我知道应该一次完成。
moo<-sqldf('SELECT id, count(id) AS idcount
FROM MyData WHERE id IS not null
GROUP BY id')
sqldf("SELECT id, idcount FROM moo
WHERE idcount = (SELECT min(idcount) FROM moo)")
答案将取决于接收 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)