日期:2014-05-17 浏览次数:20485 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-11-05 16:25:07
-- 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]([NAME] varchar(5),[VALUE] int)
insert [huang]
select 'NAME1',5 union all
select 'NAME1',4 union all
select 'NAME1',3 union all
select 'NAME2',5 union all
select 'NAME2',4 union all
select 'NAME2',3
--------------开始查询--------------------------
;WITH cte AS (
select name,ROW_NUMBER()OVER(ORDER BY name)ID
from [huang]
GROUP BY name)
SELECT cte.id,huang.*
FROM huang FULL JOIN cte ON huang.NAME=cte.name
----------------结果----------------------------
/*
id NAME VALUE
-------------------- ----- -----------
1 NAME1 5
1 NAME1 4
1 NAME1 3
2 NAME2 5
2