日期:2014-05-17 浏览次数:20493 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-11-27 16:43:40
-- 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: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([a] varchar(4),[b] varchar(1),[c] int)
insert [huang]
select '广东','a',1 union all
select '广东','b',3 union all
select '广东','c',10 union all
select '广西','a',5 union all
select '中国','f',9 union all
select '中国','g',8
--------------开始查询--------------------------
select *,(SELECT COUNT(1) FROM huang b WHERE huang.a=b.a AND huang.b>=b.b)
from [huang]
----------------结果----------------------------
/*
a b c
---- ---- ----------- -----------
广东 a 1 1
广东 b 3 2
广东 c 10 3
广西 a 5 1
中国 f 9 1
中国 g 8 2
*/
select id=identity(int,1,1),* into #tb from tb
select *,(select count(1)+1 from #tb where 项目=t.项目 and id<t.id) from #tb t