簡體   English   中英

如何使用 distinct 和 count 與 partition by

[英]How to use distinct and count with partition by

我想要具有不同 agt_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)

當前 Output 使用上述查詢:

    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

上面output中的計數是具有相同 cus_id 的行的總數,其中我想要具有相同 cus_id 的 agt_id 鏈接計數

所需的 output:

    agt_id  cus_id  Count
1   89563   93587   2
2   56139   93587   2

如果我理解正確,您需要一個簡單的 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

懷疑你想要聚合:

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;

使用 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)

暫無
暫無

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

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