[英]MySQL group by get result it does not exist in table
我的表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
嘗試這個:
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')
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.