MySQL group by get result它不存在于表中

时间:2015-04-21 06:28:16

标签: mysql

我的table1是:

   id   category cost    currentdate 

   1     type1   2400    2014-11-02
   1     type1   2400    2014-12-02
   1     type1   2100    2014-12-13
   1     type1   3000    2015-01-02
   1     type1   5000    2015-01-11
   1     type1   2000    2015-02-07
   1     type1   5500    2015-03-05
   1     type2   2700    2015-03-02
   1     type2   2000    2015-03-22

我的查询是:

select 
    ROUND(avg(cost)) as avg_cost, CONCAT(DATE_FORMAT(currentdate,'%b'),'',YEAR(currentdate)) as month ,category 
from 
    table1 
where 
    currentdate >=DATE_SUB(curdate(), INTERVAL 6 MONTH) 
group by 
    MONTH(currentdate) ,category 
order by 
    YEAR(currentdate),MONTH(currentdate) asc

我的结果为:

  avg_cost   month  category 
  nov-2014   2400   type1
  dec-2014   2250   type1
  jan-2015   2400   type1
  feb-2015   2000   type1
  mar-2015   2400   type1
  mar-2015   2350   type2

但是如果特定月份不存在类别成本,我想获得空值, 像:

   avg_cost   month  category 
   nov-2014   2400   type1
   nov-2014   null   type2
   dec-2014   2250   type1
   dec-2014   null   type2
   jan-2015   2400   type1
   jan-2015   null   type2
   feb-2015   2000   type1
   feb-2015   null   type2
   mar-2015   2400   type1
   mar-2015   2350   type2

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
  thedate.mydate   AS MY_DATE,
  avg_cost         AS AVG_COST,
  thedate.category AS CATEGORY
FROM
  (
    SELECT *
    FROM
      (
        SELECT
          DATE_FORMAT(currentdate, '%b-%Y') AS mydate,
          currentdate
        FROM table1) my1
      JOIN
      (
        SELECT category
        FROM table1) my2
    GROUP BY mydate, category
  ) thedate
  LEFT JOIN
  (
    SELECT
      ROUND(avg(cost))                  AS avg_cost,
      DATE_FORMAT(currentdate, '%b-%Y') AS mydate,
      category
    FROM table1
    GROUP BY DATE_FORMAT(currentdate, '%M-%Y'), category
  ) thedata
    ON thedate.mydate = thedata.mydate AND thedate.category = thedata.category
ORDER BY YEAR(thedate.currentdate), MONTH(thedate.currentdate), thedate.category ASC

SQL小提琴:http://sqlfiddle.com/#!9/17db7/10/0

顺便问一下,你为什么要按MONTH(currentdate)分组?我认为它应该是我DATE_FORMAT(currentdate, '%M-%Y')