我有一个这样的表:
// financial_supporter
+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
| 1 | 342 | 1000 |
| 2 | 234 | 6500 |
| 3 | 675 | 500 |
| 4 | 342 | 500 |
| 5 | 89 | 800 |
| 6 | 234 | 1500 |
| 7 | 342 | 1200 |
+----+---------+--------+
我需要选择上面表格的所有列,再加上一个名为“for_the_n_time
”的列。它应该包含用户支持我们的次数。
所以预期的结果是:
// financial_supporter
+----+---------+--------+----------------+
| id | user_id | amount | for_the_n_time |
+----+---------+--------+----------------+
| 1 | 342 | 1000 | 3 | -- for the third time
| 2 | 234 | 6500 | 2 | -- for the second time
| 3 | 675 | 500 | 1 | -- for the first time
| 4 | 342 | 500 | 2 | -- for the second time
| 5 | 89 | 800 | 1 | -- for the first time
| 6 | 234 | 1500 | 1 | -- for the first time
| 7 | 342 | 1200 | 1 | -- for the first time
+----+---------+--------+----------------+
这是我不完整的查询。我想我需要一个自连接,但我无法完全实现。
SELECT fs.*, <I don't know> as for_the_n_time
FROM financial_supporter fs
INNER JOIN financial_supporter as fs2 ON <I don't know>
WHERE 1
ORDER BY id DESC
知道我该怎么做吗?
已编辑:另外,我怎样才能使它成为这样的 DESC 顺序:
// financial_supporter
+----+---------+--------+----------------+
| id | user_id | amount | for_the_n_time |
+----+---------+--------+----------------+
| 7 | 342 | 1200 | 3 | -- for the third time
| 6 | 234 | 1500 | 2 | -- for the second time
| 5 | 89 | 800 | 1 | -- for the first time
| 4 | 342 | 500 | 2 | -- for the second time
| 3 | 675 | 500 | 1 | -- for the first time
| 2 | 234 | 6500 | 1 | -- for the first time
| 1 | 342 | 1000 | 1 | -- for the first time
+----+---------+--------+----------------+
最佳答案
您可以使用相关子查询来计算生成的列。我假设记录的日期与 id
列相关,即较早的贡献的 id
低于后来的贡献。
SELECT *,
(SELECT COUNT(*) FROM financial_supporter fs2
WHERE fs1.user_id = fs2.user_id AND fs2.id <= fs1.id) for_the_n_time
FROM financial_supporter fs1
ORDER BY id DESC;
Demo
关于mysql - 如何根据特定列计算重复行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49104389/