sql query : a category purchased immediately before and immediately after a specific category

Asked 1 years ago, Updated 1 years ago, 406 views

Hello, I'm a marketer who is using SQL little by little. I'm asking you this question because I had a hard time filling out queries during work

First, the table is as below.

TS category member number 
2022-12-22 23:08 Food 1 
2022-12-22 21:02 Electronics 2 
....... 
2022-12-23 10:10 Clothing 1

As shown above, there are each member's purchase time and purchase category! I'd like to find a category that I purchased right before and right after a specific category, so please advise me how to make a query.

EX) NULL

if there is no purchase history immediately before and after the purchase category of electronic products

sql

2022-12-26 21:19

1 Answers

Rather than trying to solve everything with queries, it's better to use it in conjunction with Excel.

I wanted to show you a real example, so I looked for a similar problem in programmers.

Get a list of products and members that have been repurchased

Let me explain based on this problem. If the customer who purchased a particular product in this matter tells you how to get the product that was purchased before/after that, you can apply the same.

(1) Recall all purchase details of the user who purchased the product.

SELECT *
FROM online_sale
JOIN (
    SELECT distinct(user_id)
    FROM online_sale
    WHERE product_id = 12
    ) target_users
ON target_users.user_id = online_sale.user_id
ORDER BY online_sale.user_id, sales_date;

This will allow you to recall all purchases made by the user who purchased item 12. If you run it in the above question, it looks like this. (Go into the link above, paste this SQL, and press the Run button. You'll understand more if you read the long-located problem on the left side of the Run button.)

(2) Process it in an Excel file.

The data you have will be much larger than this, so I'll paste this in Excel. And since the G2 cell (user_id) will be added to the F column, the next column. Line one is not data, so try putting this equation in line two. =if (AND(C3=12, F2=F3), "Product purchased before the target product", "Nothing") This ensures that the data in the second row is the same as the buyer in the third row, and that the product purchased in the third row is the target product (No. If you're satisfied with both, that's the data we wanted.

If you fill out the formula in the H2 cell in the same way, you will be able to get the product you purchased after the target product.

You have to learn too much SQL to make all this into SQL, and it often takes more time to code. So, if you are not a developer, I recommend that you use SQL for extraction and Excel for processing.


2022-12-26 23:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.