sql - MySQL - Counting transactions related to the most recent visit -
Suppose I have two tables in the same MySQL db:
The first inbound_ campaign_visit table is such that looks like.
+ ---- + ----------- + ------------------ + ------- --------------- + | ID | User_id | Inbound_campaign | Date | + ---- + ----------- + ------------------ + ------------- -------- + | 1 | 1 | 1 | 2013-02-18 13:00:00 | | 2 | 1 | 2 | 2013-02-24 13:00:00 | | 3 | 2 | 3 | 01-01-01 01:00:00 | | 4 | 2 | 2 | 2013-02-24 19: 00:00 | + ---- + ----------- + ------------------ + ------------- -------- +Clicking on this campaign's campaign results in each time a user visits my site. The "Date" column shows the time when they came to the site.
The second table is my transaction table.
+ -------- + --- ------ + --------------------- + | ID | User_id | Creation_date | + -------- + --------- + --------------------- + | 321639 | 1 | 2013-02-18 14:00:00 | | 321640 | 1 | 2013-02-24 15:00:00 | | 321641 | 1 | 2013-02-25 13:00:00 | | 321642 | 1 | 2013-04-05 12:00:00 | | 321643 | 2 | 2013-01-01 12:00:00 | | 321644 | 2 | 2013-02-23 12:00:00 | + -------- + --------- + --------------------- +A A line is created on this table whenever a transaction occurs. The "Creation_date" column indicates the time when the transaction occurred.
I want to create a report that will calculate the number of transactions per inbound campaign. The following rules must be implemented:
- A transaction is considered to be related to the inbound campaign, if user_id matches the transaction transaction and transactions within 30 days of the inbound_ campaign_visit line Happening.
- Transactions for a given user can only be applied to Inbound Campaign_Visit only recently.
The result table should look something like this:
+ - ----------------- + ----- -------------- + | Inbound_campaign | Transaction_count | + ------------------ + ------------------- + | 1 | 1 | | 2 | 2 | | 3 | 1 | + ------------------ + ------------------- +Notice that transactions 321644 and 321642 are not calculated because they rule 1 fail. Also note that transaction 321641 only applies to Inbound_ campaign 2 and not inbound_ campaign 1 (even though both campaigns fall into a 30-day restriction defined in rule 1).
I was struggling with this for some time so that any help would be appreciated. Of course I can do this in code but there should be a way to do this in SQL. TIA
SELECT an.inbound_campaign, COUNT (b.user_ID) total count inbound_ campaign_view left LEFT one a.user_ID = b.user_ID and DATEDIFF (curate) , B. Creation_data) & gt; 30 by a.inbound_campaign
Comments
Post a Comment