在日期范围内查找没有活动的客户

时间:2013-08-24 20:42:39

标签: postgresql

以下查询允许我监控在日期范围内执行的服务。我也修改它以显示最后的“X”天。

这是我的问题。我需要找到所有在日期范围内没有活动的客户。我见过使用左外连接的例子 (http://www.postgresqlforbeginners.com/2010/11/sql-outer-joins.html)并试图遵循它,但结果没有“缺失”的服务会显示。我需要看到过去“X”时间内没有看到“Bob”,而不是确实发生的活动。

所以,如果有人能看到这个并引导我找到解决方案,我会非常感激

以下是查询:

SELECT  groups.name as Office,to_char (notes.date_service,'MM/DD/YY')as DateEntered,
to_char(notes.date_creation,'MM/DD/YY')as DateService,
notes.date_creation - notes.date_service as DateDiff, 
services.code, clients.client_id,
clients.name_lastfirst_cs, staff.staff_name_cs, address.addr_county
FROM notes, services, clients, staff, groups, address
WHERE notes.zrud_service = services.zzud_service
AND notes.zrud_client = clients.zzud_client
AND notes.zrud_staff = staff.zzud_staff
AND notes.zrud_group = groups.zzud_group
AND clients.zzud_client = address.zrud_client
AND services.code IN ('10101', '10102', '10201' , '10202','10203','10204','10205','10401','10402','10403','10405') - - <I comment out this line and change it depending on the results I need >

AND groups.name = 'RCE'
AND notes.date_service BETWEEN (now() - '8 days'::interval)::timestamp AND now();  
-- this last line is also changed for diferent time spans

由于

2 个答案:

答案 0 :(得分:0)

假设客户端存储在表clients中,并且它们的活动位于notes表中,则使用NOT EXISTS(反连接):

--  I need to find all clients .....
SELECT * FROM clients
WHERE
-- ... that have had NO activity ....
  NOT EXISTS (
     SELECT 1 FROM notes
     WHERE  notes.zrud_client = clients.zzud_client
-- ...  in a date range.
       AND notes.date_service BETWEEN (now() - '8 days'::interval)::timestamp AND now()
  )

上述反连接可以这种方式转换为左外连接:

SELECT clients.* FROM clients
LEFT JOIN notes
ON ( 
     notes.zrud_client = clients.zzud_client
     AND 
     notes.date_service BETWEEN (now() - '8 days'::interval)::timestamp AND now() 
   )
WHERE 
  notes.zrud_client IS NULL

答案 1 :(得分:0)

答案的主要部分是

  • 使用正确的ANSI连接;
  • 格式化您的查询;
  • 使用表的别名;

所以你的查询变为:

select
    g.name as Office,
    to_char(n.date_service,'MM/DD/YY') as DateEntered,
    to_char(n.date_creation,'MM/DD/YY') as DateService,
    n.date_creation - n.date_service as DateDiff, 
    s.code, c.client_id,
    c.name_lastfirst_cs, st.staff_name_cs, a.addr_county
from notes as n
    inner join services as s on s.zzud_service = n.zrud_service
    inner join clients as c on c.zzud_client = n.zrud_client
    inner join staff as st on st.zzud_staff = n.zrud_staff
    inner join groups as g on g.zzud_group = n.zrud_group
    inner join address as a on a.zrud_client = c.zzud_client
where
    g.name = 'RCE' and 
    s.code in ('10101', '10102', '10201', '10202','10203','10204','10205','10401','10402','10403','10405') and
    n.date_service BETWEEN (now() - '8 days'::interval)::timestamp AND now();

但是如果你想让所有客户获得即使他们在给定时期内没有活动注释,我想你希望clients成为你查询的锚,使用left outer join并将条件移到{ {1}}代替join

where