我想选择前n个组的记录.我的数据如下所示:
表’跑步者’:
id gid status rtime --------------------------- 100 5550 1 2016-08-19 200 5550 2 2016-08-22 300 5550 1 2016-08-30 100 6050 3 2016-09-01 200 6050 1 2016-09-02 100 6250 1 2016-09-11 200 6250 1 2016-09-15 300 6250 3 2016-09-19
表’静态’
id description env ------------------------------- 100 something 1 somewhere 1 200 something 2 somewhere 2 300 something 3 somewhere 3
单元ID(id)在组内是唯一的,但在其列中不是唯一的,因为该组的实例是定期生成的.组ID(gid)分配给每个单元,但不会在多个实例上生成.
现在,组合表并选择所有内容或按特定值过滤很容易,但如何选择所有记录,例如前两个组而不直接引用组ID?
预期结果将是:
id gid description status rtime -------------------------------------- 300 6250 something 2 3 2016-09-19 200 6250 something 1 1 2016-09-15 100 6250 something 3 1 2016-09-11 200 6050 something 2 1 2016-09-02 100 6050 something 1 3 2016-09-01
额外问题:当我过滤这样的时间范围时:
[...] WHERE runner.rtime BETWEEN '2016-08-25' AND '2016-09-16'
是否有一种简单的方法可以确保群体不被切断,但是要么出现所有记录,要么根本不出现?
解决方法
您可以使用ROW_NUMBER()来执行此操作.首先,创建一个对组进行排名的查询:
SELECT gid,ROW_NUMBER() over (order by gid desc) as RN FROM Runner GROUP BY gid
然后使用它作为派生表来获取您的其他信息,并使用where子句过滤到您想要查看的组的数量.例如,下面将返回前5个组RN <= 5:
SELECT id,R.gid,description,status,rtime FROM (SELECT gid,ROW_NUMBER() over (order by gid desc) as RN FROM Runner GROUP BY gid) G INNER JOIN Runner R on R.gid = G.gid INNER JOIN Statis S on S.id = R.id WHERE RN <= 5 --Change this to see more or less groups
关于日期的第二个问题,您可以使用如下子查询来执行此操作:
SELECT * FROM Runner WHERE gid IN (SELECT gid FROM Runner WHERE rtime BETWEEN '2016-08-25' AND '2016-09-16')