我有三个表tbdata
,tbdatahw
,tbdatamr
。在所有表中,名为status
和c42
的字段相同。例如tbdatahw table
像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);
这样的冗余
我不希望2月份来两次,但我想将绿色状态值从两个feb添加到一个。我也尝试了distinct
和union
,但没有工作。我希望输出像
答案 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})