日期:2014-05-18  浏览次数:20652 次

问个排序去数问题
col1 col2 COL3
C 3 AAA
B 3 BBB
NULL 3 CCC
NULL 2 AAA
NULL 2 BBB
D 1 aaa
B 1 bbb


我想得到的是以col2分组 取col1的第一个
col1 col2 col3
C 3 AAA
NULL 2 AAA
D 1 aaa
 

------解决方案--------------------
SQL code
select distinct b.* from tb a
cross apply (select top 1 from tb where col2=a.col2) b

------解决方案--------------------
SQL code
----------------------------
-- Author  :fredrickhu(小F,向高手学习)
-- Date    :2011-11-30 16:07:21
-- Version:
--      Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) 
--    Apr 22 2011 11:57:00 
--    Copyright (c) Microsoft Corporation
--    Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
--
----------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go 
create table [tb]([col1] varchar(1),[col2] int,[COL3] varchar(3))
insert [tb]
select 'C',3,'AAA' union all
select 'B',3,'BBB' union all
select null,3,'CCC' union all
select null,2,'AAA' union all
select null,2,'BBB' union all
select 'D',1,'aaa' union all
select 'B',1,'bbb'
--------------开始查询--------------------------
select
    col1 ,col2, COL3
 from
   (select px=ROW_NUMBER()over(partition by col2 order by GETDATE()),* from tb)t
 where
   px=1
----------------结果----------------------------
/* col1 col2        COL3
---- ----------- ----
D    1           aaa
NULL 2           AAA
C    3           AAA

(3 行受影响)
*/

------解决方案--------------------
如果一定要用col1,则建议使用临时表
select * ,id = identity(int,1,1) into tmp from tb

select t.* from tb t where id = (select top 1 id from tb where col2 = t.col2 order by id)

select t.* from tb t where id = (select min(id) from tb where col2 = t.col2)

------解决方案--------------------
SQL code

create table xiaol028 (col1 char(1), col2 int, COL3 char(5))

insert into xiaol028
select 'C', 3, 'AAA' union all
select 'B', 3, 'BBB' union all
select null, 3, 'CCC' union all
select null, 2, 'AAA' union all
select null, 2, 'BBB' union all
select 'D', 1, 'aaa' union all
select 'B', 1, 'bbb'

select t.col1,t.col2,t.col3
from 
(select row_number() over(partition by col2 order by (select 0)) rn,
col1,col2,col3
from xiaol028) t
where t.rn=1
order by t.col2 desc

col1 col2        col3
---- ----------- -----
C    3           AAA  
NULL 2           AAA  
D    1           aaa  

(3 row(s) affected)