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

时间:2018-03-05 06:04:12

标签: 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
+----+---------+--------+----------------+

1 个答案:

答案 0 :(得分:1)

您可以使用相关子查询计算生成的列。我假设记录的日期与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