如何使用distinct和count与partition by

gywdnpxw  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(412)

我想要带有不同agt\u id的行以及计数。下面是我当前使用的查询,但需要帮助才能获得不同的行。

with cust as
(
SELECT customer_id, cnic
FROM customer
where customer_id 
not in 
(select agent_id from agent
where to_date(created_on) BETWEEN '2020-06-01' AND '2020-06-30')
)

select agt.agent_id, c.customer_id, c.cnic, agt.transaction_type_id, 
agt.transaction_type_name , row_number() OVER(PARTITION BY c.customer_id) AS agent_count
from cust as c
INNER JOIN konnect_ag_transaction_vw agt ON c.cnic= agt.receiver_cnic
where 
agt.status ='PROCESSED'
AND agt.transaction_type_id IN (1,2,3)

使用上述查询的当前输出:

agt_id  cus_id  Count
1   89563   93587   7
2   89563   93587   7
3   89563   93587   7
4   89563   93587   7
5   89563   93587   7
6   56139   93587   7
7   56139   93587   7

上面输出中的count是具有相同cus\u id的行的总计数,其中我需要具有相同cus\u id的agt\u id链接的计数
期望输出:

agt_id  cus_id  Count
1   89563   93587   2
2   56139   93587   2
llycmphe

llycmphe1#

如果我理解正确,您需要一个简单的group by with count()

with cust as
(
SELECT customer_id, cnic
FROM konnect_bb_customer_vw 
where customer_id 
not in 
(select agent_id from konnect_bb_agent_h_vw 
where to_date(created_on) BETWEEN '2020-06-01' AND '2020-06-30')
)

select agt.agent_id, c.customer_id, count(*)
from cust as c
INNER JOIN konnect_ag_transaction_vw agt ON c.cnic= agt.receiver_cnic
where agt.status ='PROCESSED' AND agt.transaction_type_id IN (1,2,3)
group by agt.agent_id, c.customer_id
brccelvz

brccelvz2#

我怀疑你想要:

select agt.agent_id, c.customer_id, count(*)
from cust c join
     konnect_ag_transaction_vw agt 
     on c.cnic = agt.receiver_cnic
where agt.status = 'PROCESSED' and
      agt.transaction_type_id in (1, 2, 3)
group by agt.agent_id, c.customer_id;
xyhw6mcr

xyhw6mcr3#

使用distinct关键字

select DISTINCT agt.agent_id, c.customer_id, c.cnic, agt.transaction_type_id, 
agt.transaction_type_name , row_number() OVER(PARTITION BY c.customer_id) AS agent_count
from cust as c
INNER JOIN konnect_ag_transaction_vw agt ON c.cnic= agt.receiver_cnic
where 
agt.status ='PROCESSED'
AND agt.transaction_type_id IN (1,2,3)

相关问题