当单元格不包含特定字符集

时间:2018-03-02 14:05:04

标签: sql sql-server tsql

我的数据库有一个名为Group的列。

Group可以是以下两个值之一:

  1. Group101 =主要群组
  2. Group101D1 =子组
  3. 每个小组都有两个这样的选项。

    enter image description here

    但我有些情况Group101D1存在但Group101没有。

    现在我想创建一个插入内容,我搜索的D1组没有主要组。例如,我有Group105D1但没有Group105。我想要一个插入来创建一个Group105的行。

    就我而言:

    INSERT INTO (Group)
        SELECT [Table1].[Group], [Table2].[Group]
        FROM [Table] Table1
        INNER JOIN [Table] Table2 ON [table1].[Group] = [Table2].[Group]
        -- WHERE [Table2].[Group] LIKE '%D1'
        --   AND [Table1].[Group] NOT LIKE '%D1'
    

    有些人可以帮忙,我不知道怎么做到这一点。

    我知道我可能需要使用内连接,替换和where where子句。

5 个答案:

答案 0 :(得分:0)

您需要replace此外,查询应排除已存在的行

示例数据:

 DECLARE @groups TABLE ([Group] VARCHAR(100), description VARCHAR(100))

INSERT @groups ([Group], description)
SELECT 'Group101', 'Something1'

UNION ALL

SELECT 'Group101d1', 'Something1'

UNION ALL

SELECT 'Group105d1', 'description_Bleh'

UNION ALL

SELECT 'Group2054', 'desc_2054'

UNION ALL

SELECT 'Group2054d1', 'desc_2054'

使用替换功能并排除Maingroup(如果存在)

SELECT Replace([group], 'd1', '') [Group], description
FROM @groups
WHERE [Group] NOT IN (
        SELECT p.[Group]
        FROM @groups g
        INNER JOIN @groups p
            ON g.[Group] = replace(p.[Group], 'd1', '')
        )

结果:

Group         description
Group105    description_Bleh

答案 1 :(得分:0)

您可以使用NOT EXISTSREPLACE获得所需的结果,如下所示:

INSERT INTO Table2(Group)
 select  replace([Group], 'd1', '') from Table1 a
 where [Group] like '%d1' and 
 not exists(
     select 1 from Table1 where [group] = replace(a.[Group], 'd1', '')
     )  

答案 2 :(得分:0)

如果所有子组以“D1”结尾,您可以使用以下查询插入缺少的主要组。

INSERT INTO (Group)
SELECT
left(subtable.Group,(len(subtable.Group)-len('D1')))
FROM
[Table1].[Group] subtable
where 
charindex (  'D1', subtable.Group) > 0 -- if it is sub-record
and
 not exists --check if main group exists
  (SELECT
1
FROM
[Table1].[Group] main
where (charindex (    main.Group+'D1', subtable.Group) != 0)   
)

答案 3 :(得分:0)

你刚刚用数据打包的东西

DECLARE @groups TABLE (grp VARCHAR(100), description VARCHAR(100));
INSERT @groups (grp, description) values 
         ('Group101', 'Something1')
       , ('Group101d1', 'Something1')
       , ('Group105d1', 'description_Bleh')
       , ('Group106d1', 'description_Bleh6')
       , ('Group2054', 'desc_2054')
       , ('Group2054d1', 'desc_2054');
select * from @groups order by grp; 
insert into @groups
select replace(g1.grp, 'd1', ''), g1.description 
  from @groups g1
 where g1.grp like '%d1' 
   and not exists ( select 1 
                    from @groups g2 
                    where g2.Grp = replace(g1.grp, 'd1', '') 
                  );
select * from @groups order by grp;

答案 4 :(得分:0)

我最终这样做了!

insert into Table (Group, Description)
select  replace(Group,'D1','') , description from Table
where Group like '%D1'
and replace(Group,'D1','') not in (
select Group from Table
where Group like 'Group%' and Group not like '%D1')