mysql - 如何根据特定列计算重复行?

标签 mysql sql join

我有一个这样的表:

// 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;

enter image description here

Demo

关于mysql - 如何根据特定列计算重复行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49104389/

相关文章:

mysql - 规范化使得跨多个表的连接变得困难

sql-server-2008 - SQL SERVER 2008 JOIN 提示

mysql - 简单的 SELECT 查询对于大表来说很慢

python - 通过 for 循环将从 MySQL 查询中检索到的数据放入 DataFrame pandas

mysql - 按行分割的平均响应是多少?

Javascript修改查询

php - 跨应用程序处理自然 JOINed 结果的良好实践

php - 如何在mysql中选择前三行

mysql - Django 对多个字段进行左连接查询

SQL Server View |内联 View 扩展指南