Martin AJ
Martin AJ

Reputation: 6697

How can I count duplicate rows according to specific columns?

I have a table like this:

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

I need to select all columns of table above plus one more column named "for_the_n_time". And it should be containing how many times the user has supported us.

So the expected result is:

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

Here is my query which is incomplete. I guess I need a self-join, but I cannot implement totally.

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

Any idea how can I do that?


Edited: Also how can I make it DESC order like this:

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

Upvotes: 1

Views: 55

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

You may compute your generated column using a correlated subquery. I assume that the date of the record correlates with the id column, i.e. earlier contributions would have a lower id than later contributions.

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

Upvotes: 1

Related Questions