查找与多个备用 ID 匹配条件的联接 ID

  • 本文关键字:ID 条件 备用 查找 sql oracle
  • 更新时间 :
  • 英文 :


我猜有一个快速简便的解决方案,但我尝试了许多不同的方法,并不断碰壁。尝试在这里和其他地方搜索很多,但我认为我没有使用正确的词来澄清我想知道的内容(根据我令人困惑的主题!如果这是重复或类似的,我深表歉意。

因此,为了解释这个问题(由于实际数据有些敏感而混淆),假设您有一个客户表,一个您与这些客户的会议表(会议可能有多个客户端绑定到每个客户),以及另一个表,其中包含在会议期间向这些客户收取的费用。单次会议可能会收取单项或多项费用(即咨询费、新合同费、采购费等)。

我试图找到的是系统可能错误地向客户收取相同类型费用的多个副本的任何情况,即每次会议只能收取一次的咨询费。

识别方式是查找该类型的费用(例如咨询的缺点),然后检查是否有该类型的多个不同fee_id与单个meeting_id相关联。在同一会议中,同一fee_type可能有 10 行(例如,对于参加同一会议的 10 个客户端),但它们都应绑定到同一fee_id

我尝试过的解决方案似乎要么将这些视为 10 个条目(它应该将它们算作一个),要么单独计算行并且不将它们全部分组到同一个会议中,等等。

下面是一个简单粗略的示例(尽管这是错误的,因为它没有将不同的计数分组到唯一的meeting_id中):

select c.client_name as "Client"
    , m.meeting_id as "Meeting ID"
    , m.meeting_date as "Meeting Date"
    , f.fee_type as "Fee Type"
    , count(distinct 
        (
            case when f.fee_type = 'CONS'
            then f.fee_id 
            else null 
            end
        )
    ) as "Consultation Fees Charged"
from client c
inner join meetings m
    on c.client_id = m.client_id
inner join fees f
    on m.meeting_id = f.meeting_id
where f.fee_type = ‘CONS’
group by c.client_name, m.meeting_id, m.meeting_date

确信有一个简单的解决方案,我只是错过了一些明显的东西。对不起,大量的文字。

我不是100%了解您在寻找什么。 我认为这是适用于特定客户的特定会议的某种类型的费用。 如果是这样,您的基本查询就走在正确的轨道上,但它需要group by并在case中进行一些简化(casewhere冗余):

select c.client_name as "Client", m.meeting_id as "Meeting ID", m.meeting_date as "Meeting Date",
       count(distinct f.fee_id ) as "Consultation Fees Charged"
from client c inner join
     meetings m
     on c.client_id = m.client_id inner join
     fees f
     on m.meeting_id = f.meeting_id
where f.fee_type = 'CONS'
group by c.client_name, m.meeting_id, m.meeting_date
having count(*) > 1;

要查找系统可能错误地向客户收取相同类型费用的多个副本的情况,我们可以使用GROUP BY,然后使用HAVING子句检查会议中的客户总数和每次会议的总fee_ids是否匹配。

下面的查询将返回所有此类会议,其中存在consultation fees差异

SELECT m.meeting_id as "Meeting ID", 
       m.meeting_date as "Meeting Date",
       count(f.fee_id ) as "Total Fee record count",
       count(c.client_name) as "Total Client count"
FROM client c 
INNER JOIN  meetings m
ON c.client_id = m.client_id 
INNER JOIN fees f
on m.meeting_id = f.meeting_id
AND f.fee_type = 'CONS'
group by c.client_name, m.meeting_id, m.meeting_date
having count(f.fee_id) <> count(c.client_name);

您可以通过查找客户数量和未收取费用之间的差异来检查收取的重复费用。如果为零,则没有重复费用,否则没有重复费用收取

 select count(distinct c.client_name) as "Client",
   m.meeting_id as "Meeting ID",
   m.meeting_date as "Meeting Date",
   f.fee_type as "Fee Type",
   count(distinct f.fee_id) as "Consultation Fees Charged",
   (count(distinct f.fee_id) - count(distinct c.client_name)) as "Duplicate fee charged"
      from client c
      inner join meetings m on c.client_id = m.client_id
      inner join fees f on m.meeting_id = f.meeting_id
      where f.fee_type = ‘CONS’
      group by m.meeting_id, m.meeting_date, f.fee_type

最新更新