我有一张表A,如下所示 -
Column1 Column2
0001M 80050
0001M 80053
0001M 80076
0001T 0002T
0001T 34800
0001T 34802
0001T 34804
0001T 36000
0001U 80500
0001U 80502
0001U 81105
0001U 81106
CREATE TABLE mytable(
Column1 VARCHAR(5) NOT NULL PRIMARY KEY
,Column2 VARCHAR(5) NOT NULL
);
INSERT INTO mytable(Column1,Column2) VALUES ('0001M','80050');
INSERT INTO mytable(Column1,Column2) VALUES ('0001M','80053');
INSERT INTO mytable(Column1,Column2) VALUES ('0001M','80076');
INSERT INTO mytable(Column1,Column2) VALUES ('0001T','0002T');
INSERT INTO mytable(Column1,Column2) VALUES ('0001T','34800');
INSERT INTO mytable(Column1,Column2) VALUES ('0001T','34802');
INSERT INTO mytable(Column1,Column2) VALUES ('0001T','34804');
INSERT INTO mytable(Column1,Column2) VALUES ('0001T','36000');
INSERT INTO mytable(Column1,Column2) VALUES ('0001U','80500');
INSERT INTO mytable(Column1,Column2) VALUES ('0001U','80502');
INSERT INTO mytable(Column1,Column2) VALUES ('0001U','81105');
INSERT INTO mytable(Column1,Column2) VALUES ('0001U','81106');
我有另一张表B,其中包含以下列 -
ID SubID
1 0001M
1 80050
1 80053
1 12500
2 0001T
2 0002T
2 34800
2 36000
2 12506
3 80500
3 80502
3 81106
CREATE TABLE mytable(
ID INTEGER NOT NULL PRIMARY KEY
,SubID VARCHAR(5) NOT NULL
);
INSERT INTO mytable(ID,SubID) VALUES (1,'0001M');
INSERT INTO mytable(ID,SubID) VALUES (1,'80050');
INSERT INTO mytable(ID,SubID) VALUES (1,'80053');
INSERT INTO mytable(ID,SubID) VALUES (1,'12500');
INSERT INTO mytable(ID,SubID) VALUES (2,'0001T');
INSERT INTO mytable(ID,SubID) VALUES (2,'0002T');
INSERT INTO mytable(ID,SubID) VALUES (2,'34800');
INSERT INTO mytable(ID,SubID) VALUES (2,'36000');
INSERT INTO mytable(ID,SubID) VALUES (2,'12506');
INSERT INTO mytable(ID,SubID) VALUES (3,'80500');
INSERT INTO mytable(ID,SubID) VALUES (3,'80502');
INSERT INTO mytable(ID,SubID) VALUES (3,'81106');
tableA的column1和column2的值不应同时出现在tableB的每个不同ID列中的SubID列中。如果发生这种情况,我需要标记它1.否则为0.例如,(0001M,80050)和(0001M,80053)不允许一起出现。由于这两种组合存在于表B的ID = 1中,因此应将其标记为1。
输出应该是这样的 -
ID Flag
1 1
2 1
3 0
原因标志= 0表示ID = 3 - >由于(80500,80502)和(80502,81106)仅来自column2(不是来自第1列和第2列),因此允许它们一起出现,标记为0.我使用的是SQL Server 2016版本。
答案 0 :(得分:1)
select
b1.ID,
max(case
when exists (select 1 from tableA a where a.Column1=b1.SubId and a.Column2=b2.SubId)
then 1 else 0 end) as flag
from
tableB b1
inner join table B b2 on b1.ID=b2.ID
group by b1.ID
答案 1 :(得分:0)
select b.id,
(case when count(*) > 0 then 1 else 0 end) as flag
from (select distinct b.id from b) b cross join
a join
b b1
on b1.subid = a.column1 and b1.id = b.id join
b b2
on b2.subid = a2.column2 and b2.id = b.id
group by b.id;
答案 2 :(得分:0)
你也可以使用JOINS来完成如下所示的操作。 逻辑是,如果我们从tableB获得tableA中每个列的id并且它们是相同的,那么flag应该是1
的 see live demo 强>
select
distinct B.id, flag =case when b1.id = b2.id then 1 else NULL end
from
mytableA A
left join mytableB b1 on b1.subid=a.column1
left join mytableB b2 on b2.subid=a.column2
right join
mytableB B
on B.id= case when b1.id = b2.id then b1.id else NULL end