【问题标题】:How to use distinct and count with partition by如何使用 distinct 和 count 与 partition by
【发布时间】:2020-11-16 11:35:35
【问题描述】:

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

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

    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_id 的行的总计数,其中我想要具有相同 cus_id 的 agt_id 链接计数

期望的输出:

    agt_id  cus_id  Count
1   89563   93587   2
2   56139   93587   2

【问题讨论】:

  • @AsmaDamani 。 . .我不相信你。 row_number() 不返回常量值。它返回一个枚举。你的描述有问题。另外,你的结果集有三列,但是查询返回的更多。
  • 我想在最后一个选择中添加一个不同的选项会有所帮助。

标签: sql distinct window-functions


【解决方案1】:

如果我理解正确,您需要一个简单的 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

【讨论】:

    【解决方案2】:

    怀疑你想要聚合:

    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;
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2019-10-22
        • 2021-05-06
        • 2013-12-20
        • 2020-05-02
        • 2021-12-18
        • 1970-01-01
        • 2021-03-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多