我试图根据过去18个月内的访问次数将客户与“延期”商家联系起来,其中决胜局是最近的访问日期。我在决胜局时遇到了一些麻烦。如果有两个记录根据某个MemberID的访问次数排名为1,我想在记录上将IsFirst位列设置为1,并为该MemberID设置MAX(EncounterDate)。我应该怎么做呢?
答案 0 :(得分:3)
这可能对您有所帮助......这是基于现有emp表的Oracle查询。我认为在发布问题时创建结构是个好主意。 替换第一个选择更新等...:更新您的表设置您的日期= max_date(在我的示例中为max_hire_date)WHERE your_field IN(选择我的示例中的最大日期)AND 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
答案 1 :(得分: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)
)