我有以下mysql查询:
SELECT
LEFT(MONTHNAME(date), 3) AS month,
YEAR(date) AS year,
COUNT(id) AS quantity
FROM
budgets
GROUP BY MONTH(date)
这会给我返回:
|month|year|quantity|
---------------------
| Jan|2018| 10|
| Mar|2018| 2|
| May|2018| 5|
即使COUNT(id)
不存在,我也需要显示月份
像这样:
|month|year|quantity|
---------------------
| Jan|2018| 10|
| Feb|2018| 0|
| Mar|2018| 2|
| Apr|2018| 0|
| May|2018| 5|
有人知道这样做吗?
更新
根据D-Shih的答案代码,查询返回以下内容:
|month|year|quantity|
---------------------
| Jan|2018| 10|
| Feb|null| 0|
| Mar|2018| 2|
| Apr|null| 0|
| May|2018| 5|
如果我添加不同年份的寄存器,它将仅显示名称为2017的一行,如:
|month|year|quantity|
---------------------
| Jan|2018| 10|
| Feb|null| 0|
| Mar|2018| 2|
| Apr|null| 0|
| May|2018| 5|
| May|2017| 2|
它必须显示
|month|year|quantity|
---------------------
| Jan|2018| 10|
| Feb|2018| 0|
| Mar|2018| 2|
| Apr|2018| 0|
| May|2018| 5|
| Jan|2017| 0|
| Feb|2017| 0|
| Mar|2017| 0|
| Apr|2017| 0|
| May|2017| 2|
答案 0 :(得分:0)
如果您想扩展此范围,我认为这应该可行。不确定效率如何:
SELECT a.month AS month, a.year AS year, COALESCE(b.quantity,0) AS quantity
FROM
(
SELECT DISTINCT MONTH(date) AS month, YEAR(date) AS year
FROM
budgets
) a
LEFT JOIN
(
SELECT MONTH(date) AS month, YEAR(date) AS year,
COUNT(id) AS quantity
FROM
budgets
GROUP BY MONTH(date), YEAR(date)
) b
ON a.month = b.month AND a.year = b.year
答案 1 :(得分:0)
您可以尝试制作日历表,并根据日历表 if(message.startsWith("!colorme")) { // <----
roles.some(/*..*/)
//...
}
OUTER JOIN
这是给您的样品。
模式(MySQL v8.0)
SELECT t1.month,
y.year AS year,
COUNT(t2.id)
FROM (
SELECT 'Jan' month
UNION ALL
SELECT 'Feb' month
UNION ALL
SELECT 'Mar' month
UNION ALL
SELECT 'Apr' month
UNION ALL
SELECT 'May' month
) t1
CROSS JOIN (SELECT DISTINCT YEAR(date) FROM budgets) y
LEFT JOIN budgets t2 on t1.month = LEFT(MONTHNAME(t2.date), 3)
AND y.year = YEAR(t2.date)
GROUP BY t1.month, y.year
查询#1
CREATE TABLE budgets (
`month` varchar(5),
`year` int,
quantity int
);
insert into budgets values ('Jan',2018,10);
insert into budgets values ('Mar',2018,2);
insert into budgets values ('May',2018,5);
insert into budgets values ('May',2017,2);