简体   繁体   中英

How to use distinct and count with partition by

I want rows with distinct agt_id along with the count. Following is the query i am currently using but need help to get distinct rows.

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)

Current Output using above query:

    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 in the above output is the total count of rows with same cus_id where as i want count of agt_id link with same cus_id

Desired output:

    agt_id  cus_id  Count
1   89563   93587   2
2   56139   93587   2

If I understand correctly you need a simple 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

I suspect that you want aggregation:

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;

using DISTINCT keyword as such

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM