Skip to content
Advertisement

How to compare within a partition across all possible values in MySql?

I am trying to compare values for each user per each retailer transaction. This is the input example table:

Now, I want to compare for each distinct user for the same retailer if the amount spent was within 30% across all purchases. Let’s say that the amount spent of the first and second transaction is 67% apart ($30 and $10) which is greater than the 30% threshold. However, the third row with spent of 28$ is within 30% of variance compared to the 30$ from the first row. So, these two transactions will fulfill the criteria, i.e. comparison of row 1 and row 3.

Current query:

Outout would give me null rows because it is comparing sequential transaction amounts. However, it is not accounting that row 1 and row 3 fulfill the criteria and therefore, it would return those 2 rows.

How do I adjust my query from here?

Advertisement

Answer

Consider the following…

The following query will show us all rows with no other (user_id,retailer) combination within 30% of another one (my arithmetic or logic might be slighhtly skewed but hopefuly you get the idea)…

If necessary, we can further refine this as follows

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement