我有一个数据库,其中记录了用户执行的操作,我想按ID标识从K开头到A开头(从01/01/2019到今天(20 / 06/2019),在此示例中,用户1000将其ID从K更改为A,因为K中的最后一个日期操作早于使用A的第一个操作,每个用户的userID是唯一的,这是我的表,也是用户出于相同的原因,1002的变化也很好。
我的日志表如下
ID date action USERID
KF12 01/01/2019 Create 1000
KG45 11/06/2019 Create 1002
KI89 06/05/2019 Modify 1003
AO22 20/03/2019 Delete 1000
AI88 20/06/2019 Delete 1002
..
我尝试过的地方还不完整,但是我不知道如何按周计算变更
select distinct USERID, max(DATE_USER) over (partition by USERID)
FROM
HISTORY
WHERE
USERID in (Select distinct USERID
from HISTORY
where ID like 'K%'
and DATE_USER >= to_date('1.1.' || 2019, 'DD.MM.YYYY')
and DATE_USER < to_date('20.06.' || 2019 , 'DD.MM.YYYY')
INTERSECT
select distinct USERID
from HISTORY
where ID like 'A%'
and DATE_USER >= to_date('1.1.' || 2019, 'DD.MM.YYYY')
and DATE_USER < to_date('19.06.' || 2019 , 'DD.MM.YYYY'))
and ID like 'A%'
;
在此示例中,预期结果是在(20/03 / 2019,20 / 06/2019)更改的用户(1000,1002),结果必须像这样
WEEKNUMBER COUNTOFCHANGE
25 1
12 1
答案 0 :(得分:0)
使用lag
查找上一个ID
,按'K'->'A'过滤并根据需要计数
select wk, count(distinct USERID) n
from
(select log.*, to_char(dat,'ww') wk, lag(ID) over(partition by USERID order by dat) prev_id
from log) t
where substr(t.ID,0,1) = 'A' and substr(t.prev_id,0,1) = 'K'
group by wk
答案 1 :(得分:0)
您可以尝试使用自连接来实现以下目的,而不是使用函数:
-- DATA PREPARATION
WITH LOGS(ID, "DATE",ACTION, USERID) AS
(SELECT 'KF12',TO_DATE('01/01/2019','DD/MM/RRRR'),'Create',1000 FROM DUAL UNION ALL
SELECT 'KG45',TO_DATE('11/06/2019','DD/MM/RRRR'),'Create',1002 FROM DUAL UNION ALL
SELECT 'KI89',TO_DATE('06/05/2019','DD/MM/RRRR'),'Modify',1003 FROM DUAL UNION ALL
SELECT 'AO22',TO_DATE('20/03/2019','DD/MM/RRRR'),'Delete',1000 FROM DUAL UNION ALL
SELECT 'AI88',TO_DATE('20/06/2019','DD/MM/RRRR'),'Delete',1002 FROM DUAL)
-- ACTUAL QUERY
SELECT
WK,
COUNT(DISTINCT USERID)
FROM
(
SELECT
TO_CHAR(L2."DATE", 'WW') WK,
L2.USERID
FROM
LOGS L1
JOIN LOGS L2 ON ( L1.USERID = L2.USERID
AND L1."DATE" < L2."DATE"
AND L1.ID LIKE 'K%'
AND L2.ID LIKE 'A%' )
)
GROUP BY
WK
输出:
干杯!