简体   繁体   中英

SQL Query To Obtain Values that contains multiple instances within a time range

I want to only find accounts that have more than one instance of a closed_date within their own 30 day, 3 month, and 1 year period which ends at their own monthly, quarterly, and annual expiration date. However each account has its own expiration date range. My WHERE clause is where I can't seem to figure out how to implement the proper 30 day, quarterly, and yearly range.

I'm not sure if the BETWEEN clause is appropriate or if I should be using a greater than / less than.

SELECT a.acct, COUNT(d.closed_date) AS cd, a.billing_expiration_date
FROM docupaid d
INNER JOIN account a ON a.acct=d.acct
WHERE (d.closed_date) BETWEEN (a.bill_expiration_date minus 30 days) AND a.billing_expiration_date                    
GROUP BY acct desc
HAVING cd>1

You can use DATE_SUB function:

SELECT a.acct, 
       COUNT(d.closed_date) AS cd, 
       a.billing_expiration_date
FROM docupaid d
INNER JOIN account a ON a.acct=d.acct
WHERE d.closed_date BETWEEN DATE_SUB(a.bill_expiration_date, INTERVAL 30 DAY) 
                            AND a.billing_expiration_date                    
GROUP BY acct desc
HAVING cd > 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM