sql消除空行

ddrv8njm  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(329)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

11个月前关门了。
改进这个问题
我有来自表1的数据:

AgeCount    Age      GenderCount      Gender     RaceCount    Race
-----------------------------------------------------------------------------
12          1-10     null             null       null         null 
10          11-20    null             null       null         null
null        null     3                M          null         null  
null        null     5                F          null         null
null        null     null             null       20           American Indian
null        null     null             null       10           Africa

我需要一个查询来删除 NULL 所以我会得到:

AgeCount    Age      GenderCount      Gender     RaceCount   Race
----------------------------------------------------------------------------
12          1-10     3                M          20          American Indian 
10          11-20    5                F          10          Africa

非空值可以按任何顺序联接。
我试过:

select *
from table1
where age is not null
or agecount is not null
or gendercount is not null
or gender is not null
or racecount is not null 
or race is not null

但它并没有达到预期的效果。

fhg3lkii

fhg3lkii1#

根据提供的信息,以下查询将生成所需的结果:
它连接3个子查询,每个非空组件(年龄、种族、性别)1个
它使用一个 row_number() 给出任意连接条件
它使用一个 full outer join 处理一种类型的值可能比另一种类型的值多的情况,例如,如果您添加了另一行年龄计数

declare @Test table (AgeCount int, Age varchar(16), GenderCount int, Gender varchar(1), RaceCount int, Race varchar(64));

    insert into @Test (AgeCount, Age, GenderCount, Gender, RaceCount, Race)
    values (12, '1-10', null, null, null, null)
    , (10, '11-20', null, null, null, null)
    , (null, null, 3, 'M', null, null)  
    , (null, null, 5, 'F', null, null)
    , (null, null, null, null, 20, 'American Indian')
    , (null, null, null, null, 10, 'Africa');

    select AgeCount, Age, GenderCount, Gender, RaceCount, Race
    from (
      select AgeCount, Age
        , row_number() over (order by AgeCount) row#
      from @Test
      where AgeCount is not null
    ) X
    full outer join
    (
      select GenderCount, Gender
        , row_number() over (order by GenderCount) row#
      from @Test
      where GenderCount is not null
    ) Y on Y.row# = X.row#
    full outer join (
      select RaceCount, Race
        , row_number() over (order by RaceCount) row#
      from @Test
      where RaceCount is not null
    ) Z on Z.row# = X.row#;

提供以下信息:

AgeCount    Age     GenderCount Gender  RaceCount   Race
-------------------------------------------------------------------
10          11-20   3           M       10          Africa
12          1-10    5           F       20          American Indian

相关问题