简体   繁体   English

SQL - 选择客户的第 6 次访问

[英]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.我需要能够报告访问我公司 6 次的客户,今天是第 6 次。

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.到目前为止,我已经有了这个,但这不会吸引昨天总共访问了 5 次,然后今天访问了两次的人。

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.子查询 visit_history 将选取过去恰好访问该商店 5 次的所有访客。
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.如果最后一次访问是在今天,则意味着它是第 6 次、第 7 次、第 N 次或其他什么,但重点是今天发生了第 6 次访问。

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 https://msdn.microsoft.com/en-us/library/ms176102.aspx

with rank you can apply a ranking at a column ordered by an other column.使用 rank 您可以对由其他列排序的列应用排名。 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".创建一个带有标识列的临时表,比如“visitId”。 Insert the visits into this temp table in the visit date order.按访问日期顺序将访问插入到此临时表中。

Select the one from the temp table where visitId = 6.从临时表中选择一个visitId = 6。

replace:代替:

Visit_TotalVisits = 6

by:经过:

Visit_TotalVisits >= 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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