日期:2014-05-18 浏览次数:20542 次
A a1,b1,c1 a2,b2,c2 a3,b3,c3 B a1,d1,e1 a1,d2,e2 a2,d3,e3 a2,d4,e4 已知d2>d1,d4>d3要得到 a1,d1,e1,c1 a2,d3,e3,c2 給个sql语句吧
--> 测试数据:[ta] IF OBJECT_ID('[ta]') IS NOT NULL DROP TABLE [ta] GO CREATE TABLE [ta]([a] VARCHAR(2),[b] VARCHAR(2),[c] VARCHAR(2)) INSERT [ta] SELECT 'a1','b1','c1' UNION ALL SELECT 'a2','b2','c2' UNION ALL SELECT 'a3','b3','c3' --> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([a] VARCHAR(2),[b] VARCHAR(2),[c] VARCHAR(2)) INSERT [tb] SELECT 'a1','d1','e1' UNION ALL SELECT 'a1','d2','e2' UNION ALL SELECT 'a2','d3','e3' UNION ALL SELECT 'a2','d4','e4' --------------开始查询-------------------------- SELECT b.*,a.c FROM [tb] b INNER JOIN [ta] a ON a.a=b.a AND NOT EXISTS(SELECT 1 FROM [tb] WHERE a=b.a AND b<b.b) ----------------结果---------------------------- /* a b c c ---- ---- ---- ---- a1 d1 e1 c1 a2 d3 e3 c2 (2 行受影响) */
------解决方案--------------------
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'A') BEGIN DROP TABLE A END GO CREATE TABLE A ( col1 INT, col2 INT, col3 INT ) GO INSERT INTO A SELECT 1,1,1 UNION SELECT 2,2,2 UNION SELECT 3,3,3 GO IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'B') BEGIN DROP TABLE B END GO CREATE TABLE B ( col1 INT, col2 INT, col3 INT ) GO INSERT INTO B SELECT 1,1,1 UNION SELECT 1,2,2 UNION SELECT 2,1,1 UNION SELECT 2,2,2 GO SELECT A.col1,B.col2,B.col3,A.col3 FROM B,A WHERE B.col2 <= ALL(SELECT col2 FROM B AS C WHERE B.col1 = C.col1) AND A.col1 = B.col1
------解决方案--------------------
--> 测试数据:[A1] if object_id('[A1]') is not null drop table [A1] create table [A1]([cola] varchar(2),[colb] varchar(2),[colc] varchar(2)) insert [A1] select 'a1','b1','c1' union all select 'a2','b2','c2' union all select 'a3','b3','c3' --> 测试数据:[B2] if object_id('[B2]') is not null drop table [B2] create table [B2]([cola] varchar(2),[colb] varchar(2),[colc] varchar(2)) insert [B2] select 'a1','d1','e1' union all select 'a1','d2','e2' union all select 'a2','d3','e3' union all select 'a2','d4','e4' select a.cola,b.colb,b.colc,a.colc from [A1] a inner join [B2] b on a.cola=b.cola where not exists(select 1 from [B2] c where b.cola=c.cola and c.colb<b.colb and c.colc<b.colc) /* cola colb colc colc a1 d1 e1 c1 a2 d3 e3 c2 */