mysql - 计算每个 ID 数量的比例
问题描述
这是我的桌子。类型 0 用于dislike
,类型 1 用于like
。
id | userid | postid | type
1 | 465 | 20 | 0
2 | 465 | 21 | 1
3 | 466 | 20 | 1
4 | 466 | 21 | 0
5 | 467 | 20 | 1
6 | 467 | 21 | 0
现在,我的查询是
$sql = $bdd->query('SELECT COUNT(id) AS cntLikes, postid, type FROM like_unlike WHERE type = 1 GROUP BY postid, type');
$sql = $bdd->query('SELECT COUNT(id) AS cntUnlikes, postid, type FROM like_unlike WHERE type = 0 GROUP BY postid, type');
这向我显示:
postid(20) -> 1 like
postid(21) -> 2 like1
postid(20) -> 2 dislikes
postid(21) -> 1 dislike
我想计算 %like
并为每个postid
.
$p = ($total_unlikes / ($total_unlikes+$total_likes)) * 100;
我试过了
$sql = $bdd->query("SELECT postid, COUNT(CASE type WHEN '1' THEN 1 END) AS cntLikes, COUNT(CASE type WHEN '0' THEN 1 END) AS cntunlikes from like_unlike GROUP BY postid, type");
while ($donnees2 = $sql->fetch()) {
$total_likes = $donnees2['cntLikes'];
$total_unlikes = $donnees2['cntunlikes'];
$ratio = ($total_unlikes / ($total_unlikes+$total_likes)) * 100;
echo $donnees2['postid'],' nb likes',$total_likes,' nb dislikes',$total_unlikes,' percent',$p,'<br />';}
但它显示给我
postid(20) -> nb likes 1 -> nb dislikes 0 -> percent 100
postid(20) -> nb likes 0 -> nb dislikes 2 -> percent ->100
postid(21) -> nb likes 2 -> nb dislikes 0 -> percent -> 100
postid(21) -> nb likes 0 -> nb dislikes -> 1 percent ->100
以下是我想要的最终结果:
postid(20) -> nb likes 1 -> nb dislikes 2 -> percent 33
postid(21) -> nb likes 2 -> nb dislikes 1 -> percent ->66
解决方案
type
从, 中删除GROUP BY
,这样您就不会为每种类型获得一组(和一行),而是为两种类型获得一组。
推荐阅读
- react-native - 如何在开发中的两个 Expo 应用程序之间建立深度链接?
- sql - 提高选择和插入的性能
- git - 如何在 Flutter 中引用存储库中的包?
- composer-php - Travis CI:为什么作曲家有时会安装整个包,有时不会?
- python - pydev 调试器:进程 7752 正在连接
- css - 在 React 中使用字体真棒图标作为背景图像
- python - csv.writer 编码“utf-8”,但读取编码“cp1252”
- python - python中的plt.bar生成空图
- flutter - 列表
不是 Map 类型的子类型 - java - Android 从 Firebase 消息中心重新加载 WebView URL onNewToken