日期:2014-05-17 浏览次数:20628 次
USE tempdb GO --为了简便,我略去了一些不重要的字段 CREATE TABLE test ( id INT IDENTITY(1,1), yg_bh VARCHAR(4), riqi DATETIME ) --插入测试数据,每个日期3~4条 INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-24') INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-24') INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-24') INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-25') INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-25') INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-25') INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-26') INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-26') INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-26') INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-26') --取出某组的前N条数据 DECLARE @n INT=2 SELECT * FROM test a WHERE EXISTS (SELECT 1 FROM (SELECT id,NTILE(@n) OVER(PARTITION BY CONVERT(DATE,riqi ) ORDER BY id) groups,yg_bh,riqi FROM test) b WHERE a.id=b.id AND b.groups=1)
------解决方案--------------------
SELECT test.* FROM test INNER JOIN ( SELECT id,ROW_NUMBER() OVER (PARTITION BY riqi ORDER BY id) AS XuHao FROM test) AS t ON test.id = t.id AND t.XuHao <= 2
------解决方案--------------------
或者用关联子查询也可以。
SELECT test.* FROM test WHERE test.id IN ( SELECT TOP(2) t.id FROM test AS t WHERE test.riqi = t.riqi ) /*----------- ----- ----------------------- 1 1003 2012-08-24 00:00:00.000 2 1003 2012-08-24 00:00:00.000 7 1003 2012-08-25 00:00:00.000 8 1003 2012-08-25 00:00:00.000 10 1003 2012-08-26 00:00:00.000 11 1003 2012-08-26 00:00:00.000 (6 行受影响) */
------解决方案--------------------
USE tempdb
GO
--为了简便,我略去了一些不重要的字段
CREATE TABLE test
(
id INT IDENTITY(1,1),
yg_bh VARCHAR(4),
riqi DATETIME
)
--插入测试数据,每个日期3~4条
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-24')
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-24')
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-24')
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-25')
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-25')
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-25')
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-26')
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-26')
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-26')
INSERT INTO test(yg_bh,riqi ) VALUES('1003','2012-08-26')
--取出某组的前N条数据
DECLARE @n INT=2
SELECT * FROM test a
WHERE EXISTS (SELECT 1 FROM
(SELECT id,NTILE(@n) OVER(PARTITION BY CONVERT(DATE,riqi ) ORDER BY id) groups,yg_bh,riqi
FROM test) b WHERE a.id=b.id AND b.groups=1)
id yg_bh riqi
----------- ----- -----------------------