<!--StartFragment -->這是一道面試題,覺得有點意思就發出來了。 1。如圖兩個表,上為A,下為R 一、效果一 二、效果二 三、效果三 CREATE DATABASE AR GO USE AR go CREATE TABLE A ( code INT PRIMARY KEY NOT
這是一道面試題,覺得有點意思就發出來了。
1。如圖兩個表,上為A,下為R
一、效果一
二、效果二
三、效果三
CREATE DATABASE AR GO USE AR go CREATE TABLE A ( code INT PRIMARY KEY NOT NULL, Area VARCHAR(20) ) INSERT INTO a VALUES(1,'A1') INSERT INTO a VALUES(2,'A2') INSERT INTO a VALUES(3,'A3') INSERT INTO a VALUES(5,'') INSERT INTO a VALUES(7,'') CREATE TABLE R ( code INT PRIMARY KEY NOT NULL, Area VARCHAR(20) ) INSERT INTO r VALUES(1,'R1') INSERT INTO r VALUES(3,'R3') INSERT INTO r VALUES(6,'') INSERT INTO r VALUES(8,'')
--1 select * from A union select * from R order by code
--2 select identity(int,1,1) as guid,code,Area into #1 from A select identity(int,1,1) as guid,code,Area into #2 from R select a.code as code1,a.Area as Area1,b.code as code2,b.Area as Area2 into #3 from #1 a inner join #2 b on a.guid = b.guid select * from #3
--3 select identity(int,1,1) as guid,code,Area into #1 from A select identity(int,1,1) as guid,code,Area into #2 from R select a.code as code1,a.Area as Area1,b.code as code2,b.Area as Area2 into #3 from #1 a right join #2 b on a.guid = b.guid select * from #3
--1 SELECT * FROM a UNION SELECT * FROM r
--2 SELECT m.code AS code1,m.Area AS area1,n.code AS code2,n.Area AS area2 FROM (SELECT * ,(SELECT COUNT(*)+1 FROM a a1 WHERE a1.code<a2.code) AS id FROM a a2 ) m join (SELECT * ,(SELECT COUNT(*)+1 FROM r r1 WHERE r1.code<r2.code) AS id FROM R r2) n on m.id=n.id
--3 SELECT m.code AS code1,m.Area AS area1,n.code AS code2,n.Area AS area2 FROM (SELECT * ,(SELECT COUNT(*)+1 FROM a a1 WHERE a1.code<a2.code) AS id FROM a a2 ) m LEFT join (SELECT * ,(SELECT COUNT(*)+1 FROM r r1 WHERE r1.code<r2.code) AS id FROM R r2) n on m.id=n.id