php - Mysql Percentage According to Group
问题描述
There is a table like a bottom.
+-------+---------+----------+-------+
| type | ip | line | count |
+-------+---------+----------+-------+
| x | 1 | EN | 10 |
| x | 1 | FR | 10 |
| x | 2 | EN | 5 |
| x | 5 | EN | 5 |
| y | 3 | CH | 10 |
| y | 3 | PT | 10 |
| y | 4 | PT | 10 |
| y | 6 | EN | 10 |
+-------+---------+----------+-------+
I am trying to calculate percentage of lines according to ip's which inside types. Actually count don't use for calculate the percentage, i only looking number of specific line and divide it total number of line. So, i desire to see result like this, i am giving example beside the table.
+-------+---------+----------+
| line | type | percent |
+-------+---------+----------+
| EN | x | %100 |--> There are 3 EN and 3 ip inside the X, So 3/3=%100
| FR | x | %33 |
| CH | y | %33 |
| PT | y | %66 |
| EN | y | %33 |
+-------+---------+----------+
So, i try but i couldn't reach that resul in sql.
解决方案
考虑以下...
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,line CHAR(2) NOT NULL
,type CHAR(1) NOT NULL
,ip INT NOT NULL
);
INSERT INTO my_table (line,type,ip) VALUES
('EN','x',1),
('FR','x',1),
('EN','x',2),
('EN','x',5),
('CH','y',3),
('PT','y',3),
('PT','y',4),
('EN','y',6);
SELECT line, type, COUNT(*) line_count FROM my_table GROUP BY line,type;
+------+------+------------+
| line | type | line_count |
+------+------+------------+
| CH | y | 1 |
| EN | x | 3 |
| EN | y | 1 |
| FR | x | 1 |
| PT | y | 2 |
+------+------+------------+
SELECT type, COUNT(DISTINCT ip) ip_count FROM my_table GROUP BY type;
+------+----------+
| type | ip_count |
+------+----------+
| x | 3 |
| y | 3 |
+------+----------+
然后结合以上...
SELECT a.line
, a.type
, a.line_count/b.ip_count * 100 pct
FROM
( SELECT line, type, COUNT(*) line_count FROM my_table GROUP BY line,type) a
JOIN
( SELECT type, COUNT(DISTINCT ip) ip_count FROM my_table GROUP BY type) b
ON b.type = a.type;
+------+------+----------+
| line | type | pct |
+------+------+----------+
| CH | y | 33.3333 |
| EN | x | 100.0000 |
| EN | y | 33.3333 |
| FR | x | 33.3333 |
| PT | y | 66.6667 |
+------+------+----------+
推荐阅读
- raku - 在 perl6 语法中放松空格的最佳方法是什么?
- node.js - 多次请求时出现内部服务器错误,nginx + node.js + pm2
- java - 在Spring Boot中没有外键的Rest api返回项
- docker - 如何与 docker 机器共享本地主机的文件
- sql - 如何在医院数据库中创建触发器?
- wpf - 我可以使用 ViewBox 作为 WPF 中图像的源吗?
- c# - 在 UI 上过滤 ObservableCollection 项
- python - uniq、groupby 的用例,没有排序
- sql - SQL中列值为空时如何返回默认值
- php - 将 Instagram 页面地址转换为用户名