您的位置:首页 > 数据库

取出表内分类前N条记录的SQL语句

2009-01-16 13:04 225 查看
SQL语句写法有4种。prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com1.SQL2005,情况下使用 行号 Row_Number()
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.comSELECT *
prog.Phontol.comFROM
prog.Phontol.com(
prog.Phontol.comSELECT ROW_NUMBER() OVER(PARTITION BY ct ORDER BY name) AS rnk,*
prog.Phontol.comFROM tb_name
prog.Phontol.com) AS t
prog.Phontol.comWHERE rnk<=3
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com讲解:用ROW_NUMBER() 以ct字段划分表数据,为每行数据添加行号。prog.Phontol.com然后从这个结果集里查询出行号小于等于3的记录,就是每类的前3条记录。prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com2.使用 CROSS APPLY
prog.Phontol.com
prog.Phontol.com
prog.Phontol.comSELECT DISTINCT b.*
prog.Phontol.comFROM tb_name AS a
prog.Phontol.comCROSS APPLY
prog.Phontol.com(
prog.Phontol.comSELECT TOP 3 *
prog.Phontol.comFROM tb_name
prog.Phontol.comWHERE a.ct=ct
prog.Phontol.com) AS b ORDER BY b.ct
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com讲解:主要利用CROSS APPLY,这类似join.
prog.Phontol.com
prog.Phontol.com首先在子查询里查询出表里每类的前3条记录,然后利用CROSS APPLY 和 DISTINCT ,把查询里相同的记录过滤掉。prog.Phontol.com就是前3条记录了。prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com不过这样的效率很低,不推荐使用。prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com3. 利用子查询
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.comSELECT *
prog.Phontol.comFROM tb_name AS t
prog.Phontol.comWHERE 3>(SELECT COUNT(*)
prog.Phontol.comFROM tb_name
prog.Phontol.comWHERE ct=t.ct
prog.Phontol.comAND name>t.name);
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com讲解:关键是子查询,这里类似一个while循环,每条记录去匹配和它同类的下一条记录。prog.Phontol.com计算以它开始算起记录条数,意思就是他当前所在的行号,当行号小于3的时候,证明他下面有至多3条记录,则符合子查询条件,返回到结果集里。prog.Phontol.com这样就查询出了每类的前3条记录。prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com4.这种,我没有仔细看。prog.Phontol.com就不讲解了,不过原理大概也就先是取每类的前3条记录,然后在结果集里用in最终取出结果。prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.com
prog.Phontol.comselect * from @t a
prog.Phontol.comwhere checksum(*) in (select top 3 checksum(*) from @t b where a.ct=b.ct order by name desc)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: