27,580
社区成员
发帖
与我相关
我的任务
分享
CREATE TABLE #temp
(
[type] VARCHAR(100),
other_field INT
)
INSERT #temp
SELECT '110000', 1 UNION ALL
SELECT '110000', 2 UNION ALL
SELECT '110000', 3 UNION ALL
SELECT '120000', 4 UNION ALL
SELECT '120000', 5 UNION ALL
SELECT '130000', 6 UNION ALL
SELECT '130000', 7 UNION ALL
SELECT '130000', 8
SELECT b.* FROM
(SELECT DISTINCT [type] FROM #temp) a
CROSS APPLY
(SELECT TOP(3) * FROM #temp WHERE [type] = a.[type]) b
declare @table table (Column1 int,Column2 INT)
insert into @table
select 110000,null union all
select 110000,null union all
select 110000,null union all
select 120000,null union all
select 120000,null union all
select 130000,null union all
select 130000,null
/*
Column1 Column2
----------- -----------
110000 NULL
110000 NULL
110000 NULL
120000 NULL
120000 NULL
130000 NULL
130000 NULL
*/
SELECT * FROM (
SELECT Column1 FROM @table GROUP BY Column1 UNION ALL
SELECT Column1 FROM @table GROUP BY Column1 UNION ALL
SELECT Column1 FROM @table GROUP BY Column1
)a ORDER BY a.Column1
/*
Column1
-----------
110000
110000
110000
120000
120000
120000
130000
130000
130000
*/
select * from
(select row_number() over(partition by Column1 order by getdate()) as num,* from tb) a
where num<4
select Column1,Column2
from tab a
where keycolumn in (
select top 3 keycolumn
from tab
where Column1 = a.Column1
order by keycolumn
)