我如何使用 COUNT、GROUP BY 和 HAVING 查询的 'id' 结果来执行另一个仅包含这些 ID 的查询
How do I use 'id' results of a COUNT, GROUP BY, and HAVING query to perform another query with only those ids
我有一个有 32 个 ID 的 table,每个 ID 应该有 31 行(31 个日期)。我想 select ids 及其所有日期仅适用于少于 31 行(31 个日期)的 ids。
我试过这个和其他一些东西:
SELECT id, date
FROM daily_activity
WHERE id IN(SELECT id, COUNT(id) AS num_days
FROM daily_activity
GROUP by id
HAVING num_days < 31)"
ORDER BY id, date
谢谢
一个解决方案是使用 count
作为 window function
with ids as (
select *, Count(*) over(partition by id) tot
from mytable
)
select id, date
from ids
where tot<31
你可以试试这个,也许对你有用:
SELECT id, date
FROM daily_activity
where( select COUNT(daily_activity2.id)
FROM daily_activity daily_activity2
where daily_activity.id=daily_activity2.id
group by daily_activity2.id ) < 31
ORDER BY id, date
我有一个有 32 个 ID 的 table,每个 ID 应该有 31 行(31 个日期)。我想 select ids 及其所有日期仅适用于少于 31 行(31 个日期)的 ids。
我试过这个和其他一些东西:
SELECT id, date
FROM daily_activity
WHERE id IN(SELECT id, COUNT(id) AS num_days
FROM daily_activity
GROUP by id
HAVING num_days < 31)"
ORDER BY id, date
谢谢
一个解决方案是使用 count
作为 window function
with ids as (
select *, Count(*) over(partition by id) tot
from mytable
)
select id, date
from ids
where tot<31
你可以试试这个,也许对你有用:
SELECT id, date
FROM daily_activity
where( select COUNT(daily_activity2.id)
FROM daily_activity daily_activity2
where daily_activity.id=daily_activity2.id
group by daily_activity2.id ) < 31
ORDER BY id, date