日期:2014-05-17 浏览次数:20420 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-04-27 00:11:32
-- 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,[code] int,[type] int,[访问城市] varchar(4))
insert [huang]
select 1,101,1,'北京' union all
select 2,101,3,'上海' union all
select 3,101,5,'南京' union all
select 4,102,1,'杭州' union all
select 5,102,2,'深圳' union all
select 6,103,1,'北京'
--------------开始查询--------------------------
SELECT a.id,a.[code],a.[type],a.[访问城市],b.[counts] AS 记录数
FROM huang a INNER JOIN (
select MAX(id) id,[code] ,COUNT(1) [counts]
from [huang]
GROUP BY [code])b ON a.id=b.id
----------------结果----------------------------
/*
id code type 访问城市 记录数
----------- ----------- ----------- ---- -----------
3 101 5 南京 3
5 102 2 深圳 2
6 103 1 北京 1
*/