如何根据月份获取数据?

时间:2014-02-21 14:39:17

标签: mysql sql

我已经编写了一个查询,但它根据date month year获取了数据,但我想逐月获取数据,我是怎么做到的?这是我的疑问:

select a.entered,a.credit,
(select a.account_id from listing,article r where a.account_id=r.account_id group by 
a.account_id) as article,(select a.account_id from listing,event e where 
a.account_id=e.account_id group by a.account_id) as event,a.renewal_date from listing a 
where a.profit_instructor_id='0' group by  DATE_FORMAT(a.entered,'%m-%d-%Y')

2 个答案:

答案 0 :(得分:1)

您可以使用EXTRACT()MONTH()

GROUP BY EXTRACT(MONTH FROM a.entered)
GROUP BY MONTH(a.entered)

随着您的完整查询和提取:

SELECT a.entered,
       a.credit,

  (SELECT a.account_id
   FROM listing,
        article r
   WHERE a.account_id=r.account_id
   GROUP BY a.account_id) AS article,

  (SELECT a.account_id
   FROM listing,
        event e
   WHERE a.account_id=e.account_id
   GROUP BY a.account_id) AS event,
       a.renewal_date
FROM listing a
WHERE a.profit_instructor_id='0'
GROUP BY EXTRACT(MONTH
                 FROM a.entered)

答案 1 :(得分:0)

您可以在组中使用MONTH()功能,它会将您应该与年份分组的所有年份中的月份分组

SELECT 
  a.entered,
  a.credit,
  (SELECT 
    a.account_id 
  FROM
    listing,
    article r 
  WHERE a.account_id = r.account_id 
  GROUP BY a.account_id) AS article,
  (SELECT 
    a.account_id 
  FROM
    listing,
    event e 
  WHERE a.account_id = e.account_id 
  GROUP BY a.account_id) AS event,
  a.renewal_date 
FROM
  listing a 
WHERE a.profit_instructor_id = '0' 
GROUP BY MONTH(DATE_FORMAT(a.entered, '%m-%d-%Y')),
YEAR(DATE_FORMAT(a.entered, '%m-%d-%Y'))