简体   繁体   中英

SQL - Selecting the 6th visit from a customer

I need to be able to report on clients that visited my business 6 times, the 6th time being today.

I've got this so far, but this won't pick up someone who had visited a total of 5 times yesterday, and then twice today.

SELECT Member_FullName, Branch_Name, Member_Email1, Account_Description, Visit_LastVisitDateOnly
FROM   View1
WHERE (Visit_TotalVisits = '6')
  AND (Visit_LastVisitDateOnly = CONVERT(DATE, GETDATE()))

Rows from the visits table (was asked structure of table)

VisitID BranchID    MemberID    AccountID   Visit
BF98FAC1-F430-47AD-B810-02744A1633EA    C4E833C0-7675-4650-8D58-F64DF87BB0F2    E90EC99B-8C15-4F01-AEFC-60430BE4B6BF    C404B81D-85C5-42D1-8FD2-52657960FD9A    2015-11-20 16:00:00.000
5C0CB2F0-3ED9-441F-A789-03B679FF85E7    C4E833C0-7675-4650-8D58-F64DF87BB0F2    E90EC99B-8C15-4F01-AEFC-60430BE4B6BF    C404B81D-85C5-42D1-8FD2-52657960FD9A    2015-11-20 16:00:00.000
SELECT AccountID
FROM View1 v
INNER JOIN (SELECT AccountID
            FROM Visits
            WHERE Visit < CONVERT(DATE, GETDATE())
            GROUP BY AccountID
            HAVING COUNT(1) = 5) hist ON v.AccountID = hist.AccountID
AND Visit_LastVisitDate = CONVERT(DATE, GETDATE())

Subquery visit_history will pick up all visitors who visited the shop exactly 5 times in the past.
Then it joins with the view that has last visit date. If last visit is today, means it was 6th, 7th, Nth or whatever, but the point is that 6th visit occured today.

Try something like this :

SELECT Member_FullName, Branch_Name, Member_Email1, Account_Description, Visit_LastVisitDateOnly, RANK() OVER (PARTITION BY MemberID ORDER BY Visit_ID DESC) AS Rank FROM View1 WHERE(Visit_TotalVisits = '6') AND (Rank = 6)

https://msdn.microsoft.com/en-us/library/ms176102.aspx

with rank you can apply a ranking at a column ordered by an other column. Maybe does not fit your structure right now, but you can tweak it a bit if you understand the ranking.

If you are using a stored procedure...

Create a temp table with an identity column on it, say "visitId". Insert the visits into this temp table in the visit date order.

Select the one from the temp table where visitId = 6.

replace:

Visit_TotalVisits = 6

by:

Visit_TotalVisits >= 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM