Postgres查询2个月前获取详细信息

时间:2018-04-26 08:34:17

标签: sql postgresql

我想了解使用postgresql过去两个月未访问过的客户的详细信息。以下是我的查询。我在2个月之前收到所有数据,但也想知道客户是否在两个月之间访问。如果是这样,查询结果必须不显示该客户。

select usr.name,usr.mobile,ihv.create_date,ihv.partner_id from 
invoice_header_view ihv join user_store_mapper usm on ihv.partner_id = 
usm. partner_id join public.user usr on usr.user_id = usm.user_id 
where usm.store_id = '123' and cast(ihv.create_date as date) = 
cast(now() as date) -  interval '2 month' and (cast(ihv.create_date as 
date) between cast(ihv.create_date as date) and cast(now() as 
date) - interval '2 months')

2 个答案:

答案 0 :(得分:1)

解决问题的方法之一是NOT EXISTS。您可以创建一个核心子查询,该子查询将检查invoice_header_view中是否有更新的行。

另一种方法是使用GROUP BY,例如

SELECT
    usr.name, usr.mobile, ihv.partner_id,
    max(ihv.create_date) AS max_create_date,
    count(*) AS invoice_header_count
FROM invoice_header_view ihv 
    JOIN user_store_mapper usm ON ihv.partner_id = usm.partner_id
    JOIN public.user usr ON usr.user_id = usm.user_id
WHERE
    usm.store_id = '123'
    AND ihv.create_date >= now() - interval '2 months' 
GROUP BY
    1,2,3
HAVING
    max(ihv.create_date) <= now() - interval '2 months';

答案 1 :(得分:0)

如果您希望最近日期超过两个月的客户,则可以使用:

SELECT u.name, u.mobile
FROM invoice_header_view ihv JOIN
     user_store_mapper usm
     ON ihv.partner_id = usm.partner_id JOIN
     public.user u
     ON u.user_id = usm.user_id
WHERE usm.store_id = 123   -- I'm guessing this really a number
GROUP BY u.name, u.mobile
HAVING max(ihv.create_date) <= curdate() - interval '2 months';