【问题标题】:To get distinct month name and count the values of duplicates, among multiple tables in mysql在mysql中的多个表中获取不同的月份名称并计算重复值
【发布时间】:2018-02-07 09:09:07
【问题描述】:

我可能有三张桌子tbdata,tbdatahw,tbdatamr。在所有表中,名为statusc42 的字段都是相同的。例如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。我也尝试了distinctunion,但没有成功。我想要这样的输出

【问题讨论】:

    标签: mysql sql join union


    【解决方案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})
    

    【讨论】:

    • 谢谢你。得到了答案,但在那个四月是第一个月,有可能让它订购吗?
    • 更新了我的答案 ;) > 如果你很高兴,因为它有效,非常欢迎验证操作或支持
    • 真的很开心。给你们两个:)
    猜你喜欢
    • 1970-01-01
    • 2015-11-29
    • 2020-09-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多