group_concat,GROUP BY和null值的每月值

时间:2017-09-11 16:35:05

标签: mysql

我试图每个月输出一次'即使没有付款,也可以使用group_concat在一年内付款,同时按类别进行分组。 amount是以月份排序的每月总付款的逗号分隔列表。 以下查询的当前输出是:

label     amount
NULL      0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00
Food      17.90,977.25
Transport 40.00

我无法管理将NULL标签与其他标签合并以及没有支出的列表类别。我想这可能与我加入桌子的方式有关吗?

预期输出为:

label       amount
Healthcare  0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00
Food        0.00,0.00,17.90,0.00,977.25,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00
Transport   40.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00

我目前的查询是:

select label, group_concat(payment) as amount
from(
SELECT 
categoryName as label, 
YEAR(t1.transactionDate),
t.month,
coalesce(SUM(t1.transactionAmount),0) payment
FROM
(SELECT 1 AS `month`
UNION 
SELECT 2 AS `month`
UNION  
SELECT 3 AS `month`
UNION 
 SELECT 4 AS `month`
UNION
 SELECT 5 AS `month`
UNION
 SELECT 6 AS `month`
UNION 
 SELECT 7 AS `month`
UNION 
 SELECT 8 AS `month`
UNION 
  SELECT 9 AS `month`
UNION 
  SELECT 10 AS `month`
UNION 
  SELECT 11 AS `month`
UNION 
SELECT 12 AS `month`
) AS t
LEFT JOIN transaction t1 on(t.month = MONTH(t1.transactionDate))
LEFT JOIN category USING (categoryID)
where userid = 1 or userid is null group by t.month)a group by label

任何帮助都会很棒,因为我已经有一段时间没有取得进展。 谢谢!

1 个答案:

答案 0 :(得分:0)

我认为关键是在类别和月份上使用笛卡尔联接。我没有对此进行测试,但必须接近解决方案:

select label, group_concat(monthly_sum separator ',') as amount
from (
    select c.categoryName as label, coalesce(sum(t1.payment), 0) as monthly_sum
    from category c
    join (
        SELECT 1 AS month
        UNION 
        SELECT 2 AS month
        UNION  
        SELECT 3 AS month
        UNION 
        SELECT 4 AS month
        UNION
        SELECT 5 AS month
        UNION
        SELECT 6 AS month
        UNION 
        SELECT 7 AS month
        UNION 
        SELECT 8 AS month
        UNION 
        SELECT 9 AS month
        UNION 
        SELECT 10 AS month
        UNION 
        SELECT 11 AS month
        UNION 
        SELECT 12 AS month
    ) t
    left join transaction t1 on t.month = MONTH(t1.transactionDate)
    where userid = 1 or userid is null
    group by t.month, c.categoryName
) a
group by label