0

我正在尝试根据过去 18 个月内的访问次数将客户链接到“首选”商家,其中决胜局是最近的访问日期。我对决胜局有点麻烦。如果有两条记录都基于某个 MemberID 的访问次数排名 1,我想在该 MemberID 的 MAX(EncounterDate) 记录上将 IsFirst 位列设置为 1。我该怎么做呢?

4

2 回答 2

3

这可能会对您有所帮助... 这是基于现有 emp 表的 Oracle 查询。我认为在发布问题时创建结构是个好主意。将第一个选择替换为更新等...:更新您的表设置您的日期 = max_date(在我的示例中为 max_hire_date)WHERE your_field IN(在我的示例中选择最大日期)并且 rnk = 1 和 rno = 1

SELECT * FROM 
 (  
 SELECT deptno
      , ename
      , sal
      , RANK() OVER (PARTITION BY deptno ORDER BY sal desc) rnk 
      , ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY sal desc) rno 
      , MAX(hiredate) OVER (PARTITION BY deptno ORDER BY deptno) max_hire_date
   FROM emp_test
  WHERE deptno = 20
 ORDER BY deptno
 )
 WHERE rnk = 1
   --AND rno = 1 -- or 2 or any other number...
/

SQL>

DEPTNO  ENAME   SAL    RNK  RNO HIREDATE    MAX_HIRE_DATE
-----------------------------------------------------------
 20     SCOTT   3000    1   1   1/28/2013   1/28/2013
 20     FORD    3000    1   2   12/3/1981   1/28/2013
于 2013-01-28T19:04:27.773 回答
0

假设某些表的结构,以下 SQL 获取您想要的信息:

select c.*, NumVisits, MaxVisitDate, MaxFirstVisitDate
       (select count(*)
        from visits v
        where v.customerid = c.customerid and 
              v.visi
from customers c join
     (select customerid,
             sum(case when visitdate between getdate() - 365*1.5 and getdate()
                      then 1 else 0
                  end) as NumVisits,
             max(visitdate) as MaxVisitDate,
             max(case when IsFirst = 1 then visitdate end) as MaxFirstVisitDate
      from visits
      group by customerid
     ) v
     on c.customerid = v.customerid

从这些信息中,您可以将您想要做的事情的逻辑放在一起。当 时MaxVisitDate = MaxFirstVisitDate,则在最近的日期设置该位。

您的更新问题的答案是这样的:

update visits
    set IsFirst = 1
    where exists (select max(encounterDate)
                  from visits v2
                  where v2.customer_id = visits.customer_id
                  having max(encounterDate) = visits.encounterDate)
                 )
于 2013-01-28T18:46:03.287 回答