SQL添加月份

时间:2014-05-28 15:51:44

标签: mysql add time-series

您好我正在尝试获取某些月份的记录。例如,对于此查询,我希望用户看到当前月份“May”和过去一个月将是“April”。从那时起,我不希望我的查询在任何其他月份运行。我坚持这个查询,无法弄明白。基本上我需要一个函数在我的查询中自动知道这个月和1个月前显示记录。谢谢

DECLARE @Year int
set @Year = 2014
SELECT d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone

   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 1 THEN 1 ELSE NULL END) January
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 2 THEN 1 ELSE NULL END) Feburary
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 3 THEN 1 ELSE NULL END) March
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 4 THEN 1 ELSE NULL END) April
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 5 THEN 1 ELSE NULL END) May
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 6 THEN 1 ELSE NULL END) June
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 7 THEN 1 ELSE NULL END) July
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 8 THEN 1 ELSE NULL END) August
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 9 THEN 1 ELSE NULL END) September
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 10 THEN 1 ELSE NULL END) October
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 11 THEN 1 ELSE NULL END) November
   , COUNT(CASE WHEN  MONTH(c.Funded_date) = 12 THEN 1 ELSE NULL END) December
   , COUNT(*) 'Year to Date'
   FROM tdealer a 
   JOIN tContact b ON a.contact_id = b.contact_id 
   JOIN tContract c ON a.dealer_id = c.dealer_id 
   JOIN tCompany d ON c.company_id = d.company_id
  where YEAR (c.Funded_date) = @Year
  GROUP BY d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone

1 个答案:

答案 0 :(得分:0)

这里的诀窍是做两件事:

  1. 创建一个表达式,将任意DATETIME转换为发生该日期的月份的第一天。

  2. WHEREGROUP BY条款中正确使用它。

  3. 表达式是

    DATE_FORMAT(whatever, '%Y-%m-01')
    

    这需要,例如' 2014-05-28 12:22:30',并将其转换为' 2014-05-01'。将一个有效的DATE转换为另一个有效的DATE非常方便,因为这样你就可以使用MySQL内置的所有良好日期算法。

    因此,例如,如果您想要在本月之前的第一个月中使用它:

    DATE_FORMAT(NOW(), '%Y-%m-01') - INTERVAL 1 MONTH
    

    以下是您的查询大纲:

    SELECT DATE_FORMAT(c.Funded_date, '%Y-%m-01') AS month_beginning,
           d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone,
           COUNT(1) AS itemcount
      FROM tdealer a 
      JOIN tContact b ON a.contact_id = b.contact_id 
      JOIN tContract c ON a.dealer_id = c.dealer_id 
      JOIN tCompany d ON c.company_id = d.company_id
     where c.Funded_date >= DATE_FORMAT(NOW(), '%Y-%m-01') - INTERVAL 1 MONTH
       AND c.Funded_date <  DATE_FORMAT(NOW(), '%Y-%m-01') + INTERVAL 1 MONTH
     GROUP BY DATE_FORMAT(c.Funded_date, '%Y-%m-01'),
              d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone
     ORDER BY d.name, a.dealer_code, b.last_name, b.city, b.state, b.phone,
              DATE_FORMAT(c.Funded_date, '%Y-%m-01')
    

    看看你如何选择两个月的时间?它从本月前一个月的第一天开始,到下个月的第一天结束,但不包括那一天。

    如何做这类事情是在http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

    上写的