在MySQL日期函数中获取一个空日期的值。

问题描述 投票:0回答:1

我有以下MySQL查询

SELECT SUM( mc_gross ) AS total, MONTH( transaction_datetime ) AS months 
FROM users_payment 
WHERE 1 AND YEAR( transaction_datetime ) = '2020' 
GROUP BY MONTH( transaction_datetime ) , YEAR( transaction_datetime )

我得到的输出是

total month
34.90 2
4.95 3
49.85 4
14.85 5

然而,我想看看,如果我可以创建下面的输出,只是从MySQL查询?

total month
0.00 1
34.90 2
4.95 3
49.85 4
14.85 5
 0.00 6
 0.00 7
 0.00 8
 0.00 9
 0.00 10
 0.00 11
 0.00 12
mysql sql
1个回答
1
投票

你可以使用 RIGHT JOIN 与...作对 表情 全部12个值。

例如:

select
  coalesce(q.total, 0.0) as total,
  m.n as month
from ( -- your query here
  SELECT SUM( mc_gross ) AS total, MONTH( transaction_datetime ) AS months
  FROM users_payment 
  WHERE 1 AND YEAR( transaction_datetime ) = '2020' 
  GROUP BY MONTH( transaction_datetime ) , YEAR( transaction_datetime )
) q
right join (
  select 1 as n union all select 2 union all select 3 
  union all select 4 union all select 5 union all select 6
  union all select 7 union all select 8 union all select 9
  union all select 10 union all select 11 union all select 12
) m on q.months = m.n
order by m.n
© www.soinside.com 2019 - 2024. All rights reserved.