简体   繁体   中英

How to pull data from database table for previous month only

I want to show records for previous month only, excluding this month's dates.For example, today is February 5th and I want to show records for January 1st to 31st

i have a table- tbl_order_details where I need to fetch all order records by current month and previous month respectively. the column name for date type is orderDate this is what I an doing for fetching rows for current month till date:

SELECT COUNT(1) 
FROM tbl_order_details 
where merchantCode= '$user_code'
AND MONTH(orderDate) = MONTH(CURRENT_DATE()) 
AND YEAR(orderDate) = YEAR(CURRENT_DATE()) 

But I cant figure out how do I show records for january that does not include any records from February

SELECT * FROM tbl_order_details
    WHERE YEAR(orderDate) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
    AND MONTH(orderDate) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)

Avoid using DATE (), MONTH (), DAY (), YEAR (), SUBSTR (), LEFT (), RIGHT (), LIKE when mentioning columns in WHERE or JOIN'S because you no longer use the indexes that exist in the columns mentioned. Ex: WHERE YEAR(orderDate) = ... Avoid doing this for the reasons stated above.

I suggest use as follows ...

If your "orderDate" column is of type date, do as follows:

SELECT COUNT(1) 
FROM tbl_order_details 
where merchantCode= '$user_code'
AND orderDate BETWEEN DATE_ADD(LAST_DAY(NOW() - INTERVAL 2 MONTH), INTERVAL 1 DAY)
AND LAST_DAY(DATE_ADD(LAST_DAY(NOW() - INTERVAL 2 MONTH), INTERVAL 1 DAY));

Will return the first day of the previous month

DATE_ADD(LAST_DAY(NOW() - INTERVAL 2 MONTH), INTERVAL 1 DAY)

Returns the last day of the previous month

LAST_DAY(DATE_ADD(LAST_DAY(NOW() - INTERVAL 2 MONTH), INTERVAL 1 DAY))

For writing a PHP code, you can get the Month and Year from PHP itself by using the strtotime function depending upon the input your table takes and then formatting it in your sql query. For eg.:

<?php
$month = date("M", strtotime("previous month"));
$year = date("Y", strtotime("this year"));
$query_get = 'SELECT COUNT(1) FROM tbl_order_details where merchantCode= {$user_code} AND MONTH(orderDate) = {$month} AND YEAR(orderDate) = {$year}'
?>

And further pass $query_get to your DB query to fetch the required result. Or else, you can straight push the following query as @Rohit suggested above.

<?php
$query_get = 'SELECT * FROM tbl_order_details WHERE YEAR(orderDate) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(orderDate) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)'
?>

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