簡體   English   中英

tableA 中的值數量不在 tableB 中?

[英]Number of values in tableA not in tableB?

我有兩個具有以下架構的表:

CREATE TABLE tableA 
(
    accountNumber, --has colons in between values... need to be removed on join
    type, --(1,2,3,4,5,6,7,8,9,10)
    status1,
    status2
);
CREATE TABLE tableB 
(
    accountNumber,
    usage, -- [0,inf)
    day_id
);

我想知道 tableA 中有多少 accountNumbers 不在 tableB 中。 我已經構建了兩種方法來做到這一點: Way #1

with cteA as (

Select upper(replace(accountNumber, ':',''))) as accountNumber,
       type
from tableA
where status1 = 'Active'
and status2 = 'Active'
and type in ('1','2','3','4')
),
cteB as (
Select distinct accountNumber 
from tableB
where usage > 0 
and day_id > '2022-01-01'
),
cte as (
Select a.accountNumber,
       b.accountNumber,
       a.type
from tableA a
left join tableB b 
on a.accountNumber = b.accountNumber
where b.accountNumber is null)
select type, count(*)
from cte
group by 1
order by 2 desc;  

方式#2

select type,
       count(distinct accountNumber),
       count(distinct accountNumber) filter (where upper(replace(accountNumber,':','')) in (select accountNumber from tableB where day_id > '2022-01-01' and usage > 0))
from tableA
where status1 = 'Active'
and status2 = 'Active'
and type in ('1','2','3','4')
group by 1  

據我所知,這些應該給我相同的答案。 當然,方式 2 需要我做減法(手動在 excel 或在我的腦海中)......但我不明白為什么這些查詢會給我一個不同的值? 我錯過了什么嗎?

如果我正確理解你的問題,那么應該有更簡單的方法。 怎么樣:

select count(distinct accountNumber)
from tableA
where not exists(select 1 from tableB where tableA.accountNumber = tableB.accountNumber)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM