简体   繁体   中英

I want to retrieve last year record from MySQL database but it's retrieving all data's from database

string cmd = @"
SELECT Status,COUNT(Status),YEAR(Start_Date_Time) As LASTYEAR 
FROM sh_report 
WHERE 'YEAR(Start_Date_Time)' <= DATE_SUB(CURDATE(),INTERVAL 1 YEAR) 
GROUP BY YEAR(Start_Date_Time)";

Problem is getting all record but i want only last one year record from database can any one please tel me MYSQL Query to get last one year record.

选择前1个,然后使用asc子句使用order

You need to use the LIMIT to get what you want. Here is more info on the LIMIT .

     SELECT Status,COUNT(Status),YEAR(Start_Date_Time) As LASTYEAR 
     FROM sh_report 
     WHERE YEAR(Start_Date_Time) <= DATE_SUB(CURDATE(),INTERVAL 1 YEAR) 
     GROUP BY YEAR(Start_Date_Time)
     ORDER BY YEAR(Start_Date_Time) Asc
     LIMIT 1

The where clause of the query is comparing the YEAR component of Start_Date_Time as string with date string returned by the DATE_SUB function. Please refer to the MySQL manual . Your where clause could be like this -

YEAR(Start_Date_Time) >= YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)

Hope this helps!!

I think it should be corrected with following at where clause

WHERE 'YEAR(Start_Date_Time)' >= DATE_SUB(CURDATE(),INTERVAL 1 YEAR)

So it would be like,

string cmd = "SELECT Status,COUNT(Status),YEAR(Start_Date_Time) As LASTYEAR FROM sh_report WHERE 'YEAR(Start_Date_Time)' >= DATE_SUB(CURDATE(),INTERVAL 1 YEAR) GROUP BY YEAR(Start_Date_Time)";

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