[英]How to get count of instances in a one to many relationship across multiple tables?
I have a query where I am attempting to find multiple instances of a custtype for a specific date. 我有一个查询,尝试在特定日期查找一个客户类型的多个实例。 The following query works fine as is:
以下查询可以正常运行:
select idm, count(*) totals
from customer.purch a
where exists (select null
from customer.name b
where b.idad = a.id
and custdate = to_date('5/11/2017', 'MM/DD/YYYY')
and custtype = 'R'
)
group by idm
having count(*) > 1;
The issue I am having however, is I am not sure how to expand the above query to find different combinations of custtype on the given date. 但是我遇到的问题是我不确定如何扩展上述查询以在给定日期查找不同的客户类型组合。 For example, how can i get the query to give me the idm of a record where at least one custype is R and at least one other custype is 'Z'?
例如,我如何获取查询以给我一个记录的idm,其中至少一个客户类型是R而至少另一个客户类型是“ Z”? I figure a self join on the customer.name field might be the correct way to go, but I am not sure how to implement it.
我认为在customer.name字段上进行自我联接可能是正确的方法,但是我不确定如何实现它。 Thank you for your time.
感谢您的时间。
Sample Data 样本数据
Table customer.purch a
_______________
|idm | id |
| 1 | 896 |
| 2 | 207 |
| 3 | 359 |
________________
Table customer.name b
______________________________
|idad | custdate |custtype|
| 896 | 5/11/2017 | R |
| 896 | 5/11/2017 | Z |
| 207 | 5/11/2017 | R |
| 207 | 5/11/2017 | X |
| 359 | 5/11/2017 | R |
| 359 | 5/11/2017 | Z |
| 359 | 5/11/2017 | R |
| 359 | 5/11/2017 | R |
_______________________________
Output
______________
|IDM | count |
| 1 | 2 |
| 3 | 4 |
_______________
If I understand correctly, you can use aggregation and a having
clause: 如果我理解正确,则可以使用聚合和
having
子句:
select p.idm, count(*) totals
from customer.purch p join
customer.name n
on p.id = n.idad
where n.custdate = date '2017-05-11'
group by p.idm
having sum(case when n.custtype = 'R' then 1 else 0 end) > 0 and
sum(case when n.custtype = 'Z' then 1 else 0 end) > 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.