我正在使用 MySQL 5.7,并且想計算在特定時間為用戶編輯的帖子的百分比。
通常,我會將其作為兩個單獨的查詢來執行,但我很確定可以通過單個查詢來完成。我有一組用戶編輯了帖子,并希望計算每個用戶編輯帖子的數量。像這樣:
select count(*) as edited_post_count,
user_id
from posts
where edited_at between '2022-05-31' and '2022-06-06'
group by user_id
order by edited_post_count desc;
現在,我想弄清楚他們有史以來的帖子總數,以便能夠說在此期間編輯了 80 個帖子中的 10 個。如果他們沒有編輯,edited_at 將為空(yes 應該是 last_edited_at)。我怎么能把它添加到這個查詢中?
帖子
| ID | 身體 | 用戶身份 | 已編輯 |
|---|---|---|---|
| 1 | “什么” | 1 | 2022-06-01 |
| 2 | “曾經” | 1 | 無效的 |
| 3 | “更多的” | 2 | 2022-06-03 |
uj5u.com熱心網友回復:
您可以使用在您的日期范圍內CONCAT輸出COUNT由單個用戶分組的帖子,并與子查詢連接,該子查詢獲取edited_at IS NOT NULL未指定日期范圍的帖子總數。
select
count(*) as edited_post_count,
CONCAT(count(*), ' of ', (SELECT COUNT(*) from posts a where a.user_id = b.user_id and edited_at is not null), ' posts were edited during this time.') as total_post_count,
user_id
from posts b
where edited_at between '2022-05-31' and '2022-06-06'
group by user_id
order by edited_post_count desc;
示例結果:
| 已編輯帖子計數 | total_post_count | 用戶身份 |
|---|---|---|
| 3 | 在此期間編輯了 5 個帖子中的 3 個。 | 1 |
| 2 | 在此期間編輯了 3 個帖子中的 2 個。 | 2 |
如果你想要它作為一個百分比,將你的個人計數除以你的總計數乘以 100。
(count(*)/(SELECT COUNT(*) from posts a where a.user_id = b.user_id and edited_at is not null))*100 as total_post_count_percent,
db<>fiddle here。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/504983.html
