我有FM_TBL表,该表的month_id列是数字数据类型,日期以“ YYYYMM”格式存储。
我想比较上个月和当月的数据,并以此为基础找出当月插入FM_TABLE的新行数。
答案 0 :(得分:2)
您可以使用减号
select SYS_DB_NAME, ENTITY_ID, MONTH_ID
from my_table
where MONTH_ID = to_char(sysdate, 'YYYY') || lpad( extract(month from sysdate), 2,'0')
minus
select SYS_DB_NAME, ENTITY_ID, MONTH_ID
from my_table
where MONTH_ID = to_char(sysdate, 'YYYY') || lpad( (extract(month from sysdate) -1) , 2,'0')
,如果需要行内容
select * from my_table m
inner join (
select SYS_DB_NAME, ENTITY_ID, MONTH_ID
from my_table
where MONTH_ID = to_char(sysdate, 'YYYY') || lpad( extract(month from sysdate), 2,'0')
minus
select SYS_DB_NAME, ENTITY_ID, MONTH_ID
from my_table
where MONTH_ID = to_char(sysdate, 'YYYY') || lpad( (extract(month from sysdate) -1) , 2,'0')
) T on m.SYS_DB_NAME = t.SYS_DB_NAME
AND m.ENTITY_ID = t.ENTITY_ID
AND m.MONTH_ID = t.MONTH_ID
,如果您只需要计数
select count(*) from
inner join (
select SYS_DB_NAME, ENTITY_ID, MONTH_ID
from my_table
where MONTH_ID = to_char(sysdate, 'YYYY') || lpad( extract(month from sysdate), 2,'0')
minus
select SYS_DB_NAME, ENTITY_ID, MONTH_ID
from my_table
where MONTH_ID = to_char(sysdate, 'YYYY') || lpad( (extract(month from sysdate) -1) , 2,'0')
) T
答案 1 :(得分:1)
您可以使用not exists
:
select count(*)
from fm_tbl t
where t.monthid = to_char(sysdate, 'YYYYMM') and
not exists (select 1
from fm_tbl t2
where t2.monthid = to_char(sysdate - interval '1' month, 'YYYYMM') and
t2.cust_srcid = t.cust_srcid
);
如果可以在给定的月份内回头客,请使用count(distinct cust_srcid)
。