【发布时间】:2018-02-07 09:09:07
【问题描述】:
我可能有三张桌子tbdata,tbdatahw,tbdatamr。在所有表中,名为status 和c42 的字段都是相同的。例如tbdatahw table
喜欢tbdata and tbdatamr table 中的相同字段。字段状态 1 指定绿色,2 指定黄色,c42 指定日期详细信息。我尝试实现的是在 1 月份,所有 3 张桌子中有多少绿色黄色状态。我在工作台中尝试了这个查询
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 月份出现两次,但我想将 2 月份的绿色状态值加为 1。我也尝试了distinct 和union,但没有成功。我想要这样的输出
【问题讨论】: