首页 > 解决方案 > SQL将查询合二为一

问题描述

我有几个插入查询:

insert into table2 (age, name)
    select '0-19', 'abc'
    where not exists (select 1 from table2 where age is null  and name is null);

insert into table2 (age, name)
    select '20-29', 'zxy'
    where not exists (select 1 from table2 where age not in ( '0-19')  and name is null);

insert into table2 (age, name)
    select '30-39', 'egt'
    where not exists (select 1 from table2 where age not in ( '0-19', '20-29')  and name is null);

insert into table2 (age, name)
    select '40-49', 'aaa'
    where not exists (select 1 from table2 where age not in ( '0-19', '20-29', '30-39')  and name is null);

insert into table2 (age, name)
    select '50-59', 'rtg'
    where not exists (select 1 from table2 where age not in ( '0-19', '20-29', '30-39', '40-49')  and name is null);

insert into table2 (age, name)
    select '60+', 'ghg'
    where not exists (select 1 from table2 where age not in ( '0-19', '20-29', '30-39', '40-49', '50-59')  and name is null);

如果满足相关条件,我想插入数据。你可以看到他们分开查询。将这些查询重写为一个查询。谢谢

我可以尝试与任何人进行测试,无论nvarcharinteger.

标签: sqlsql-server

解决方案


不确定以下是否有帮助。

SELECT
    CASE WHEN Age IN ("00-19") 
     THEN ("0-19")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("20-29") 
     THEN ("20-29")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("30-39") 
     THEN ("30-39")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("40-49") 
     THEN ("40-49")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("50-59") 
     THEN ("50-59")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("60-69") 
     THEN ("60-69")
     ELSE ("NULL")
    END AS Age
FROM table2

不知道上面有没有帮助。会鼓励你解释你正在尝试做什么,然后每个人都可以提供帮助。


推荐阅读