日期:2014-05-17 浏览次数:20661 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-25 15:24:58
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([id] int,[zd1] int,[zd2] int)
insert [A]
select 1,111,111 union all
select 2,222,222
--> 测试数据:[B]
if object_id('[B]') is not null drop table [B]
go
create table [B]([aid] int,[zd3] varchar(3),[zd4] varchar(3))
insert [B]
select 1,'www','www' union all
select 1,'sss','sss' union all
select 2,'qqq','qqq' union all
select 2,'eee','eee'
--------------开始查询--------------------------
select a.*,b.zd3,b.zd4 from [A] a INNER JOIN (SELECT aid,MAX(zd3)zd3,MAX(zd4)zd4 FROM b GROUP BY aid) b ON a.id=b.aid
----------------结果----------------------------
/*
id zd1 zd2 zd3 zd4
----------- ----------- ----------- ---- ----
1 111 &