我有 2 個表用戶和帖子,我只需要擁有超過 3 個帖子和超過 5 個帖子的用戶數量。
我需要這樣的東西:
| 用戶數 | 帖子 |
|---|---|
| 555 | >3 |
| 888 | >5 |
SELECT
COUNT( u.Id)
FROM
Users u
INNER JOIN Posts p ON (u.Id=p.OwnerId)
HAVING COUNT(p.Id)>3
我試試這個,但我認為計數不起作用。
uj5u.com熱心網友回復:
您可以使用兩個級別的聚合
select sum(case when cnt > 3 then 1 else 0 end) cnt_3,
sum(case when cnt > 5 then 1 else 0 end) cnt_5
from (select ownerid, count(*) cnt from posts group by ownerid) p
請注意,您不需要帶入users桌子;該posts表包含我們需要的所有資訊。
根據您的資料庫,語法快捷方式可能可用,如 MySQL 中:
select sum(cnt > 3) cnt_3,
sum(cnt > 5) cnt_5
from (select ownerid, count(*) cnt from posts group by ownerid) p
或在 Posgres 中:
select count(*) where(cnt > 3) cnt_3,
count(*) where(cnt > 5) cnt_5
from (select ownerid, count(*) cnt from posts group by ownerid) p
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/524163.html
下一篇:MYSQL中基于多列的累積和
