SQL:一行中存在任一指标就显示出来

       当想要统计的两个指标不在一张表中时,需要做关联。但很多情况下,也没有办法保证其中一张表的维度是全的,用left join或right join可能会导致数据丢失。所以借助full join处理。

1)如,将下面的数据处理成表格中的效果(维度就是name)。
样例数据
目标效果:

name number show_number
A 300 0.80
B 100 NULL
C 150 0.20
D NULL 0.66
select if(r.name is null ,r.name2,r.name) as name, -- 保留有值的name
       r.number,
       r.show_number
from 
(   -- 数据合并
    select t1.name,t1.number,t2.name as name2,t2.show_number
     from 
        (select 'A' as name,300 as number
            union all select 'B' ,100
            union all select 'C' ,150 
        ) as t1
        full join 
        (select 'A' as name,0.8 as show_number
            union all select 'D',0.66
            union all select 'C',0.2
        ) as t2 on t1.name=t2.name
) as r

结果 :
结果
2)如果再增加一个维度type的话:

select if(r.name is null ,r.name2,r.name) as name, -- 保留有值的name
       if(r.type is null ,r.type2,r.type) as type,
       r.number,
       r.show_number
    --   r.type2
from 
(   -- 数据合并
    select t1.name,t1.number,t1.type,t2.name as name2,t2.show_number,t2.type as type2
     from 
        (select 'A' as name,300 as number,'red' as type
            union all select 'B' ,100,'red'
            union all select 'C' ,150 ,'red'
        ) as t1
        full join 
        (select 'A' as name,0.8 as show_number,'red' as type
            union all select 'D',0.66,'green'
            union all select 'C',0.2,'green'
        ) as t2 on t1.name=t2.name and t1.type=t2.type
) as r

结果:
在这里插入图片描述

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-16 18:30:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-16 18:30:04       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-16 18:30:04       82 阅读
  4. Python语言-面向对象

    2024-01-16 18:30:04       91 阅读

热门阅读

  1. 用python实现调用nosql

    2024-01-16 18:30:04       48 阅读
  2. Linux 文本处理三剑客:grep、sed 和 awk

    2024-01-16 18:30:04       42 阅读
  3. Kafka学习

    2024-01-16 18:30:04       56 阅读
  4. SpringBoot 原理深入及源码剖析

    2024-01-16 18:30:04       41 阅读
  5. 从“Linux VS Laxcus谁更强”说开去

    2024-01-16 18:30:04       54 阅读
  6. TensorFlow是由Google开发的开源深度学习框架

    2024-01-16 18:30:04       55 阅读
  7. 网络安全产品之认识防火墙

    2024-01-16 18:30:04       63 阅读