我正在尝试构建一种纸张文件。对于我有以下表格:Mysql计算来自不同行的团队的排名
队
CREATE TABLE `teams` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`creator_id` int(11) NOT NULL,
`friend_id` int(11) DEFAULT NULL,
`team_name` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
);
team_log
CREATE TABLE IF NOT EXISTS `progress_tracker` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`user_id` int(8) NOT NULL,
`team_id` int(11) NOT NULL,
`date` date NOT NULL,
`clues_found` int(11) NOT NULL,
`clues_to_find` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
- 每队由两个用户组成;
- 每个用户从可找到的可变数量的线索开始;
- clues_found可以增加或减少。不保证最高的数字是最新的;
我需要根据用户在加入后找到的线索的平均数(以百分比表示)(针对团队中的两个用户) - clues_found表示最大日期的行减去具有最低日期的记录上的clues_found)。
举例来说,如果我有每个表的以下数据:
队表数据
+--------+------------+------------+---------------+
| id | creator_id | friend_id | team_name |
+--------+------------+------------+---------------+
| 1 | 25 | 28 | Test1 |
| 2 | 31 | 5 | Test2 |
+--------+------------+------------+---------------+
team_log表数据
+--------+---------+---------+------------+-------------+---------------+
| id | user_id | team_id | date | clues_found | clues_to_find |
+--------+---------+---------+------------+-------------+---------------+
| 1 | 25 | 1 | 2013-01-6 | 3 | 24 |
| 2 | 25 | 1 | 2013-01-8 | 7 | 24 |
| 3 | 25 | 1 | 2013-01-10 | 10 | 24 |
| 4 | 28 | 1 | 2013-01-8 | 5 | 30 |
| 5 | 28 | 1 | 2013-01-14 | 20 | 30 |
| 6 | 31 | 2 | 2013-01-11 | 6 | 14 |
| 7 | 5 | 2 | 2013-01-9 | 2 | 20 |
| 8 | 5 | 2 | 2013-01-10 | 10 | 20 |
| 9 | 5 | 2 | 2013-01-12 | 14 | 20 |
+--------+---------+---------+------------+-------------+---------------+
所需的结果
+-------------+---------------------+
| team_id | team_percentage |
+-------------+---------------------+
| 1 | 39,58333333 |
| 2 | 30 |
+-------------+---------------------+
作为参考,这是一个中间表示这可能有助于理解:
+-------------+---------+---------------------+
| user_id | team_id | precentage_per_user |
+-------------+---------+---------------------+
| 25 | 1 | 29,16666667 |
| 28 | 1 | 50 |
| 31 | 2 | 0 |
| 5 | 2 | 60 |
+-------------+---------+---------------------+
到目前为止,我有以下SQL:
SELECT STRAIGHT_JOIN
tl2.team_id, (tl2.weight - tl1.weight)*100/tl2.clues_to_find
from
(select
team_id,user_id,clues_found
FROM
`team_log`
where 1
group by
team_id, user_id
order by
`date`) base
join (select team_id, user_id, clues_found, clues_to_find from `team_log` where user_id = base.user_id and team_id = base.team_id group by team_id, user_id order by `date` desc) tl2
但这返回为我的错误m不允许在第二个查询中使用base.user_id。我也不是很确定我正朝着正确的方向前进。
任何人都可以帮忙吗?
请添加后“team_log表数据”称号断行,所以我们可以看到它正确 – Roy
完成。感谢您的支持 – jribeiro
您能否解释一下这句话:“我需要根据用户加入后发现的线索的平均数(以百分比表示)获得队伍的排名(对于团队中的两个用户) - clues_found在最大日期的行上减去最低日期的记录上的clues_found)。“当我将它应用到团队2时,我得到了-12 - 找到的总线索是32,平均值是8.然后我减去14和6. –