sql - Count number of distinct values based on another set of distinct values
问题描述
I am trying to count a set of values based on another distinct value set:
-----------------------------------------------------
|CusID |Agent1 |Agent2 |Agent 3 |Agent 4 |Agent 5 |
-----------------------------------------------------
|1 |Pat |Pat |Jane |Simon |Jane |
|2 |Pater |Pat |Simon |Simon |Pat |
|1 |Jane |Jane |Simon |Pat |Pat |
|3 |Simon |Simon |Jane |Pat |Peter |
|3 |Jane |Simon |Pat |Pater |Pat |
-----------------------------------------------------
I want to get:
----------------------------------------------------------------------------
|CusIDUnq |AgentName|Count|AgentName|Count|AgentName|Count|AgentName|Count|
----------------------------------------------------------------------------
|1 |Pat |4 |Jane |4 |Simon |2 |Peter |0 |
|2 |Pat |2 |Jane |0 |Simon |2 |Pater |1 |
|3 |Pat |3 |Jane |2 |Simon |3 |Peter |2 |
----------------------------------------------------------------------------
How can I do this using SQL?
Thanks in advance!
edit: I need to tell that the number of customers and agents could change over time. So, I think a solution like below is also fine with me. The point is, I can't code the agent names or customer IDs into the query.
-----------------------
|CusID|AgentName|Count|
-----------------------
|1 |Pat |4 |
|1 |Jane |4 |
|1 |Simon |2 |
|2 |Pat |2 |
|2 |Simon |2 |
|2 |Peter |1 |
etc. Here, I need to omit 0 results where an agent is not listed for a specific customer.
Again, many thanks!
解决方案
如果我理解正确,你可以这样做:
select id,
sum(case when 'Pat' in (Agent1, Agent2, Agent3, Agent4, Agent5)
then 1 else 0 end
end) as num_pat,
sum(case when 'Jane' in (Agent1, Agent2, Agent3, Agent4, Agent5)
then 1 else 0 end
end) as num_jane,
sum(case when 'Simon' in (Agent1, Agent2, Agent3, Agent4, Agent5)
then 1 else 0 end
end) as num_simon,
sum(case when 'Peter' in (Agent1, Agent2, Agent3, Agent4, Agent5)
then 1 else 0 end
end) as num_peter
from t
group by id;
这会将计数与代理名称放在列名称中,但这似乎是您想要的。
推荐阅读
- javascript - 我可以访问由 Ant Design Table 生成的分页组件的道具或状态吗?
- python - Catboost 分类器在拟合时出现错误
- javascript - JavaScript:在 XML 和 JSON 字符串中插入换行符和空格?
- r - Rshiny App 在一个事件上多次更新文本输入
- reactjs - 为什么 react-day-picker onDayClick 给出没有重载匹配这个 cal 错误?
- ios - Vue-Nativescript Back-Navigation 使 iOS 应用程序崩溃
- android - 在 Android 的 Scroll 上使用 SnapHelper 时出现抖动/弹跳效果
- testing - 如何将 TestCafé 测试组织成多个步骤?
- html - Angular 6-如何在没有指针事件时显示工具提示
- python - 使用 Python 下载 NSE 2021 数据