日期:2014-05-16  浏览次数:20430 次

多条相同记录取其中某一字段最小的
情景:
表A 
字段1     字段2     字段 3
  1        01      2012-04-03
  1        02      2012-04-03
  2        03      2012-06-13
  2        05      2012-05-23
需求:找出相同字段1中字段3最小的记录
select 字段1,min(字段3) from A group by 字段1  得到:
 字段1     字段3
   1      2012-04-03
   2       2012-05-23
问题:
请问如何得知结果中每条记录对应的字段2
------解决方案--------------------
----------------------------------------------------------------
-- Author  :fredrickhu(小F,向高手学习)
-- Date    :2014-03-05 16:34:47
-- Verstion:
--      Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) 
-- Jul  9 2008 14:43:34 
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go 
create table [tb]([字段1] int,[字段2] varchar(2),[字段3] datetime)
insert [tb]
select 1,'01','2012-04-03' union all
select 1,'02','2012-04-03' union all
select 2,'03','2012-06-13' union all
select 2,'05','2012-05-23'
--------------开始查询--------------------------
select * from tb t where not exists(select 1 from tb where 字段1=t.字段1 and (字段3<t.字段3 OR 字段3=t.字段3 AND 字段2<t.字段2))
----------------结果----------------------------
/* 字段1         字段2  字段3
----------- ---- -----------------------
1           01   2012-04-03 00:00:00.000
2           05   2012-05-23 00:00:00.000

(2 行受影响)

*/