日期:2014-05-17 浏览次数:20652 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-04-14 17:26:14
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (Intel X86)
-- Jun 17 2011 00:57:23
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([ID] int,[客户] varchar(1),[订单时间] datetime,[地点] varchar(4))
insert [huang]
select 1,'A','2011-1-3','上海' union all
select 2,'B','2011-2-4','北京' union all
select 3,'C','2011-2-9','天津' union all
select 4,'B','2011-2-20','上海' union all
select 5,'C','2011-5-6','广州' union all
select 6,'A','2011-6-8','成都' union all
select 7,'A','2011-8-15','上海'
--------------开始查询--------------------------
SELECT *
FROM [huang] a
WHERE EXISTS(SELECT 1 FROM (
select [客户],MAX([订单时间])[订单时间]
from [huang]
GROUP BY [客户])b WHERE a.[客户]=b.[客户] AND a.[订单时间]=b.[订单时间])
ORDER BY [订单时间] DESC
----------------结果----------------------------
/*
ID 客户 订单时间 地点
----------- ---- ----------------------- ----
7 A 2011-08-15&n