34,593
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
go
--> 测试数据:[table2]
if object_id('[table2]') is not null drop table [table2]
go
CREATE TABLE table1
(
id varchar(8) primary key,
name varchar(64)
);
CREATE TABLE table2
(
sd varchar(12) primary key,
id varchar(8) foreign key (id) references table1(id),
aaa varchar(64)
);
insert [table1]
select '00000001','a' union all
select '00000002','b' union all
select '00000003','c' union all
select '00000004','d'
insert [table2]
select 'dfgsdfg','00000001',56756 union all
select 'sdghggt','00000001',56776 union all
select 'yuhfggg','00000002',58736 union all
select 'fgfghgh','00000003',56596 union all
select 'jkhjkjk','00000003',56676
GO
SELECT b.sd AS sd,a.id,a.name,b.aaa
from table1 AS a,[table2] AS b
where b.[id]=a.[id]
AND NOT exists(SELECT 1 FROM table2 WHERE ID=b.ID AND aaa<b.aaa)
AND NOT EXISTS(SELECT 1 FROM table2 WHERE ID=b.ID AND aaa=b.aaa AND sd<b.sd)
ORDER BY ID
/*
sd id name aaa
dfgsdfg 00000001 a 56756
yuhfggg 00000002 b 58736
fgfghgh 00000003 c 56596
*/
select
MIN(b.sd) AS sd,a.id,a.name,b.aaa
from table1 AS a,table2 AS b
where b.[id]=a.[id]
GROUP BY a.id,b.aaa,a.name
order by b.aaa
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2011-09-28 15:39:09
-- Verstion:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86)
-- Apr 22 2011 11:57:00
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
--
----------------------------------------------------------------
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
go
create table [table1]([col1] varchar(8),[col2] varchar(1))
insert [table1]
select '00000001','a' union all
select '00000002','b' union all
select '00000003','c' union all
select '00000004','d'
--> 测试数据:[table2]
if object_id('[table2]') is not null drop table [table2]
go
create table [table2]([col3] varchar(7),[col1] varchar(8),[col4] int)
insert [table2]
select 'dfgsdfg','00000001',56756 union all
select 'sdghggt','00000001',56776 union all
select 'yuhfggg','00000002',58736 union all
select 'fgfghgh','00000003',56596 union all
select 'jkhjkjk','00000003',56676
--------------开始查询--------------------------
select
b.col3,a.*,b.col4
from
table1 a join table2 b
on
a.col1=b.col1
and
b.col4=(select MIN(col4) from table2 where col1=b.col1 )
----------------结果----------------------------
/* col3 col1 col2 col4
------- -------- ---- -----------
dfgsdfg 00000001 a 56756
yuhfggg 00000002 b 58736
fgfghgh 00000003 c 56596
(3 行受影响)
*/
select a.sd,a.id,b.name,a.aaa
from table2 a inner join table1 b on a.id=b.id
where not exists(select 1 from table2 where id=a.id and aaa<a.aaa)