如何从2个表的2列之间选择相交?

时间:2019-05-24 09:32:03

标签: tsql join

a 我想选择两个表中都可用的FROM TO范围 例如:在VAL = 3000 TABLE_A介于3000-9999之间,TABLE_B介于0-4000之间 因此,两者之间的截距将为3000-4000。 如何完成此任务?

CREATE TABLE TABLE_A(
 A_ID NVARCHAR,
 B_ID SMALLINT,
 A_FROM SMALLINT,
 A_TO SMALLINT)


 CREATE TABLE TABLE_B(
 B_ID SMALLINT,
 VAL SMALLINT,
 B_FROM SMALLINT,
 B_TO SMALLINT)

INSERT INTO TABLE_A(A_ID,B_ID,A_FROM,A_TO)
VALUES (N'A',1,0,3000),
    (N'A',2,3000,9999);

INSERT INTO TABLE_B(B_ID,VAL,B_FROM,B_TO)
VALUES (1,1000,0,2000),
       (1,2000,2000,9999),
       (2,3000,0,4000),
       (2,4000,4000,9999)

SELECT A_ID,
       A.B_ID,
       VAL,
       A_FROM AS 'FROM',
       A_TO AS 'TO'
FROM  TABLE_A AS A
INNER JOIN TABLE_B AS B
ON A.B_ID = B.B_ID;

1 个答案:

答案 0 :(得分:0)

类似这样

SELECT A_ID,
       A.B_ID,
       VAL,
       A_FROM AS 'FROM',
       A_TO AS 'TO' , 
       CASE WHEN A.A_FROM >= B.B_FROM THEN A.A_FROM ELSE B.B_FROM END AS start , 
       CASE WHEN  A.A_TO >= B.B_TO THEN B.B_TO ELSE A.A_TO END AS finish 

FROM  #TABLE_A AS A
INNER JOIN #TABLE_B AS B
ON A.B_ID = B.B_ID;