日期:2014-05-17 浏览次数:20606 次
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 b
GROUP BY a.A,b.B
ORDER 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)
------解决方案--------------------
declare @test table(A int, B varchar(4))
insert into @test
select 1, 'x1' union
select 1, 'x2' union
select 2, 'x3' union
select 2, 'x4' union
select 2, 'xxx5' union
select 3, 'xxx' union
select 3, 'xxxx'
select A,B from
(
select row_number() over(partition by A order by A) rn,* from @test
) t
where t.rn=1
/*
A B
----------- ----
1 x1
2 x3
3 xxx
*/
------解决方案--------------------
-->测试数据
IF OBJECT_ID('tab') IS NOT NULL
DROP TABLE tab
GO
CREATE TABLE tab(A INT,B VARCHAR(10))
INSERT INTO tab
SELECT '1','x1' UNION ALL
SELECT '1','x2' UNION ALL
SELECT '2','x3' UNION ALL
SELECT '2','x4' UNION ALL
SELECT '2','xxx5' UNION ALL
SELECT '3','xxx' UNION ALL
SELECT '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
*/
------解决方案--------------------
SELECT * FROM test a
WHERE EXISTS (SELECT 1 FROM
(SELECT A,NTILE(1) OVER(ORDER BY A) groups
FROM test) b WHERE a.A=b.A AND b.groups=1)