首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求条sql话语 急等

2012-09-10 
求条sql语句急等AB1x11x22x32x42xxx53xxx3xxxx表中有个字段 AB有多条记录我只想要期中的第一条得到的结果

求条sql语句 急等
A B
1 x1
1 x2
2 x3
2 x4
2 xxx5
3 xxx
3 xxxx

表中有个字段 A B 有多条记录
我只想要期中的第一条

得到的结果是

A B
1 x1
2 x3
3 xxxx
这个SQL怎么写


[解决办法]

SQL code
SELECT a.A,b.B FROM t1 AS a    CROSS APPLY(SELECT TOP 1 B FROM t1 AS x WHERE x.A=a.A) AS bGROUP BY a.A,b.BORDER BY a.A
[解决办法]
;with cte as (
select rn=row_number() over(partition by a order by getdate()),* from t
)
select * from t where rn=1;

[解决办法]
select * from tb a where b in(select top 1 b from tb where id=a.id)
[解决办法]
SQL code
declare @test table(A int, B varchar(4))insert into @testselect 1, 'x1' unionselect 1, 'x2' unionselect 2, 'x3' unionselect 2, 'x4' unionselect 2, 'xxx5' unionselect 3, 'xxx' unionselect 3, 'xxxx'select A,B from(    select row_number() over(partition by A order by A) rn,* from @test) twhere t.rn=1/*A           B----------- ----1           x12           x33           xxx*/
[解决办法]
SQL code
-->测试数据IF OBJECT_ID('tab') IS NOT NULLDROP TABLE tabGOCREATE TABLE tab(A INT,B VARCHAR(10))INSERT INTO tabSELECT '1','x1' UNION ALLSELECT '1','x2' UNION ALLSELECT '2','x3' UNION ALLSELECT '2','x4' UNION ALLSELECT '2','xxx5' UNION ALLSELECT '3','xxx' UNION ALLSELECT '3','xxxx' GO--select  * from tab-->查询;with cte as (select rn=row_number() over(partition by A order by B),* from tab)select * from cte where rn=1/*   A    B   1    x1   2    x3   3    xxx*/
[解决办法]
SQL code
SELECT * FROM test a WHERE EXISTS (SELECT 1 FROM (SELECT A,NTILE(1) OVER(ORDER BY A) groupsFROM test) b WHERE a.A=b.A AND b.groups=1) 

热点排行