iSun 发表于 2013-1-4 01:30:30

SQL Server 分组后取Top N

<div class="postcontent"><div id="cnblogs_post_body">  近日,工作中突遇一需求:将一数据表分组,而后取出每组内按一定规则排列的前N条数据。乍想来,这本是寻常查询,无甚难处。可提笔写来,终究是困住了笔者好一会儿。冥思苦想,遍查网络,不曾想这竟然是SQL界的一个经典话题。今日将我得来的若干方法列出,抛砖引玉,以期与众位探讨。
  正文之前,对示例表结构加以说明。
http://images.cnitblog.com/blog/53642/201212/22211813-6af32ecf5e6c4f90bd85edfe0842e1f9.jpg
                    表SectionTransactionLog,用来记录各部门各项活动的日志表
                     SectionId,部门Id
                     SectionTransactionType,活动类型
                     TotalTransactionValue,活动花费
                     TransactionDate,活动时间
  我们设定的场景为:选出每部门(SectionId)最近两次举行的活动。
  笔者用来测试的SectionTransactionLog表中数据超3,000,000。
一、 嵌套子查询方式
1
<div class="cnblogs_code">1 SELECT * FROM SectionTransactionLog mLog2 where 3   (select COUNT(*) from SectionTransactionLog subLog4   where subLog.SectionId = mLog.SectionId and subLog.TransactionDate >= mLog.TransactionDate)<=25 order by SectionId, TransactionDate desc
页: [1]
查看完整版本: SQL Server 分组后取Top N