简体   繁体   中英

MySQL Query results based on month

I really need some help. Not MySQL friendly, muddled through this last few days but now stuck...

Need to take the below query and modify it to pull out only records closed in month of "January" for instance. Is this possible from the below? Cant figure it...

<?php
$recentlyClosedDays = 7;
?>


$query1 = "
SELECT HD_TICKET.ID as ID, 
HD_TICKET.TITLE as Title, 
HD_STATUS.NAME AS Status, 
HD_PRIORITY.NAME AS Priority, 
HD_TICKET.CREATED as Created, 
HD_TICKET.MODIFIED as Modified, 
S.FULL_NAME  as Submitter, 
O.FULL_NAME  as Owner, 
HD_TICKET.RESOLUTION as Resolution,
(SELECT COMMENT FROM HD_TICKET_CHANGE WHERE HD_TICKET_ID=HD_TICKET.ID ORDER BY TIMESTAMP DESC LIMIT 1) as Comment,
HD_TICKET.CUSTOM_FIELD_VALUE0 as Type  
FROM HD_TICKET  
JOIN HD_STATUS ON (HD_STATUS.ID = HD_TICKET.HD_STATUS_ID) 
JOIN HD_PRIORITY ON (HD_PRIORITY.ID = HD_TICKET.HD_PRIORITY_ID) 
LEFT JOIN USER S ON (S.ID = HD_TICKET.SUBMITTER_ID) 
LEFT JOIN USER O ON (O.ID = HD_TICKET.OWNER_ID)
WHERE (HD_TICKET.HD_QUEUE_ID = $mainQueueID)
AND (HD_STATUS.STATE like '%Closed%')  
AND (HD_TICKET.TIME_CLOSED >= DATE_SUB(NOW(), INTERVAL $recentlyClosedDays DAY))
ORDER BY HD_TICKET.TIME_CLOSED DESC
";

Any help would be greatly apprecaited and beer will be owed :)

To select DATE , DATETIME , or TIMESTAMP values in the current month , you do this.

WHERE timestampval >= DATE(DATE_FORMAT(NOW(), '%Y-%m-01'))
  AND timestampval <  DATE(DATE_FORMAT(NOW(), '%Y-%m-01')) + INTERVAL 1 MONTH

For the previous month you can do this:

WHERE timestampval >= DATE(DATE_FORMAT(NOW(), '%Y-%m-01')) - INTERVAL 1 MONTH
  AND timestampval <  DATE(DATE_FORMAT(NOW(), '%Y-%m-01')) 

For the previous year you could do this:

WHERE timestampval >= DATE(DATE_FORMAT(NOW(), '%Y-01-01')) - INTERVAL 1 YEAR
  AND timestampval <  DATE(DATE_FORMAT(NOW(), '%Y-01-01')) 

You can summarize (aggregate) tables by month like this:

SELECT DATE(DATE_FORMAT(timestampval , '%Y-%m-01')) AS month_starting,
       SUM(whatever) AS total,
       COUNT(whatever) AS transactions
  FROM table
 GROUP BY DATE(DATE_FORMAT(timestampval , '%Y-%m-01'))

This all works because this expression:

DATE(DATE_FORMAT(sometime, '%Y-%m-01'))

takes an arbitrary sometime value and returns the first day of the month in which the timestamp occurs. Similarly,

DATE(DATE_FORMAT(sometime, '%Y-01-01'))

returns the first day of the year. You can then use date arithmetic like + INTERVAL 1 MONTH to manipulate those first days of months or years.

Here's a more complete writeup on this topic. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

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