[英]SQL- Add up all the values in a resulting column and calculate the percentage using another column in the same query
我發現很難在標題中描述我的問題,但是在這里我會更加清楚。 我有兩個表users_friends
和active_users
...這是兩者的架構
CREATE TABLE `users_friends` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`friend_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `friend_id_user_id_index` (`friend_id`,`user_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7967354 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `active_users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`first` varchar(155) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=150948970 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
我想查看關注1個人,2個人,3個人等的active_users
的百分比
我運行了此查詢,使我得到了跟隨X人數的用戶數
( SELECT count(t.total_follows) AS users_count, t.total_follows FROM ( ( SELECT count(*) total_follows, active_users.id FROM active_users INNER JOIN users_friends on users_friends.user_id = active_users.id GROUP BY active_users.id ) AS t ) GROUP BY t.total_follows ORDER BY t.total_follows )
這是結果
users_count total_follows
5 1
3 2
2 3
我可以通過修改上面的查詢並像這樣匯總users_count
來獲得users_count
列的總和
select SUM(t1.users_count) as total_sum from ( < insert above query> ) as t1
但我不知道如何計算users_count
列的總和除以users_count
,這將為我提供如下所示的所需結果
users_count total_follows percentage
5 1 50.0
3 2 30.0
2 3 20.0
我知道我可以通過這樣做來獲得此列值
(count(t.total_follows) / 10) * 100 as percentage
但我無法對查詢中的總和(10)進行硬編碼。 我需要查詢才能在1次運行中計算所有內容。 如何修改查詢以實現此目的?
您可能想嘗試使用“ with”語句:
WITH x as
(
SELECT count(t.total_follows) AS users_count,
t.total_follows
FROM ( ( SELECT count(*) total_follows, active_users.id
FROM active_users
INNER JOIN users_friends on users_friends.user_id = active_users.id
GROUP BY active_users.id ) AS t )
GROUP BY t.total_follows
ORDER BY t.total_follows )
)
SELECT *, COUNT/(SELECT SUM(users_count) FROM x)::FLOAT percentage from x
我最終只是計算所有列的總和,並將它們存儲在一個名為@total_sum
的變量中,然后在第二個查詢中使用它……如果我可以使用WITH
語句(如@Stoddard Meigs建議的),那會很好。我的mysql版本不支持
set @total_sum = (select SUM(t1.users_count) as total_sum from ( ( SELECT
count(table1.total_follows) AS users_count, table1.total_follows FROM ( (
SELECT count(*) total_follows, active_users.id FROM active_users INNER JOIN
users_friends on users_friends.user_id = active_users.id GROUP BY
active_users.id ) AS table1 ) GROUP BY table1.total_follows ORDER BY
table1.total_follows ) ) as t1);
( SELECT count(table1.total_follows) AS users_count, table1.total_follows,
(count(table1.total_follows) / @total_sum) * 100 as percentage FROM ( ( SELECT
count(*) total_follows, active_users.id FROM active_users INNER JOIN
users_friends on users_friends.user_id = active_users.id GROUP BY
active_users.id ) AS table1 ) GROUP BY table1.total_follows ORDER BY
table1.total_follows )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.