获取不同的月份名称并计算mysql中多个表中重复项的值

时间:2018-02-07 09:09:08

标签: mysql sql join union

我有三个表tbdatatbdatahwtbdatamr。在所有表中,名为statusc42的字段相同。例如tbdatahw table enter image description here

tbdata and tbdatamr table中的相同字段一样。字段状态1指定绿色,2表示黄色,c42表示日期详细信息。我尝试实现的是1月份在所有3个表中有多少绿色黄色状态。我在workbench

中尝试了这个查询
    SELECT  MONTHNAME(c42) MONTH, SUM( case when status = 0 THEN 1 else 0 end) AS red
,SUM( case when status = 1 THEN 1 else 0 end) AS green
,SUM( case when status = 2 THEN 1 else 0 end) AS yellow
FROM  tbdata where  month(c42) is not null group by month(c42)
union all 
SELECT  MONTHNAME(c42) MONTH, SUM(distinct case when status = 0 THEN 1 else 0 end) AS red
,SUM(distinct case when status = 1 THEN 1 else 0 end) AS green
,SUM(distinct case when status = 2 THEN 1 else 0 end) AS yellow
FROM  tbdatamr where  month(c42) is not null group by month(c42)
union all 
SELECT  MONTHNAME(c42) MONTH, SUM(distinct case when status = 0 THEN 1 else 0 end) AS red
,SUM(distinct case when status = 1 THEN 1 else 0 end) AS green
,SUM(distinct case when status = 2 THEN 1 else 0 end) AS yellow
FROM  tbdatahw where  month(c42) is not null group by month(c42);

它为输出提供了像enter image description here

这样的冗余

我不希望2月份来两次,但我想将绿色状态值从两个feb添加到一个。我也尝试了distinctunion,但没有工作。我希望输出像enter image description here

1 个答案:

答案 0 :(得分:1)

    select month, 
SUM(t.red) as red, 
SUM(t.green) as green, 
SUM(t.yellow) as yellow 
from ( {put your whole query here} ) as t GROUP BY month ORDER BY FIELD(month, 'JANUARY', 'FEBRUARY',{please continue to DECEMBER})