简体   繁体   中英

how to get total items having date difference of more than 7

I have to do a mysql statement to get total items having date difference of more than 7 from today (means today - 7)

This is my current statement:

SELECT 
    COUNT(*)
FROM 
    complaints 
WHERE 
    complaint_status = 'OPEN' AND 
    complaint_regdate <= curdate()
    complaint_regdate >= DATE_SUB(curdate(),INTERVAL 7 day)

I am getting this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'complaint_regdate >= DATE_SUB(curdate(),INTERVAL 7 day)' at line 1

You are missing an AND operator in your sql.

SELECT COUNT(*) FROM complaints WHERE complaint_status = 'OPEN' AND complaint_regdate <= curdate() AND complaint_regdate >= DATE_SUB(curdate(),INTERVAL 7 day)

You can use the BETWEEN operator for this

SELECT COUNT(*) 
FROM complaints 
WHERE complaint_status = 'OPEN' 
  AND complaint_regdate < (CURDATE() - INTERVAL 7 day)

Note you don't need the DATE_SUB function, you can just use a normal subtraction. Also these will only work if your complaint_regdate is a DATE column. If it's a DATETIME column you will need to use NOW() rather than CURDATE() or extract just the date pat of the field values.

It sounds like you're asking for the query to find the count where the date is more than 7 days in the past. Your current query listed above shows the count for everything within the last 7 days. So here is the query for more than 7 days past:

SELECT COUNT(*) FROM complaints WHERE complaint_status = 'OPEN' AND complaint_regdate < DATE_SUB(curdate(),INTERVAL 7 day)

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