我的数据库有一个名为Group
的列。
此Group
可以是以下两个值之一:
Group101
=主要群组Group101D1
=子组每个小组都有两个这样的选项。
但我有些情况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子句。
答案 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 EXISTS
和REPLACE
获得所需的结果,如下所示:
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')