日期:2014-05-18 浏览次数:20628 次
select a.ID,a.Name,a.ClassID,t.value from A a inner join( select Number,Value,State from( select px=row_number()over(partition by Number order by Value),* from B where State=0)s where px=1)t on t.Number=a.ID
------解决方案--------------------
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'A') BEGIN DROP TABLE A END GO CREATE TABLE A ( ID VARCHAR(10), Name VARCHAR(10), Address VARCHAR(10), ClassID VARCHAR(10) ) GO INSERT INTO A SELECT '1-1', '张三', '武汉', '0123' UNION SELECT '1-2', '王五', '长沙', '0123' IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'B') BEGIN DROP TABLE B END GO CREATE TABLE B ( Number VARCHAR(10), Value INT, State INT ) GO INSERT INTO B SELECT '1-1', 2, 0 UNION SELECT '1-1', 3, 0 UNION SELECT '1-2', 2, 1 GO SELECT ID,Name,ClassID,Value FROM A,(SELECT Number,MIN(value) AS value FROM B WHERE State = 0 GROUP BY Number) AS C WHERE A.ID = C.Number ID Name ClassID Value 1-1 张三 0123 2
------解决方案--------------------
if object_id('[tb_A]') is not null drop table [tb_A] create table [tb_A] insert [tb_A] SELECT '1-1', '张三', '武汉', '0123' UNION ALL SELECT '1-2', '王五', '长沙', '0123' if object_id('[tb_B]') is not null drop table [tb_B] create table [tb_B] INSERT [tb_B] SELECT '1-1', 2, 0 UNION ALL SELECT '1-1', 3, 0 UNION ALL SELECT '1-2', 2, 1 SELECT ID,Name,ClassID,Value FROM tb_A,(SELECT Number,MIN(value) AS value FROM tb_B WHERE State=0 GROUP BY Number) AS tb_C WHERE tb_A.ID = tb_C.Number ID Name ClassID Value 1-1 张三 0123 2