在项目中需要显示一个广告位的使用记录,此时字段order_no(广告位序号)字段可能出现多个,但是我们根据其有效期来取值(在时间段内,只有一个是有效的),因此,考虑使用ROW_NUMBER () OVER(PARTITION BY order_no ORDER BY START_Time ASC)方式,分组后取值。
1.获取广告历史记录
SELECT TOP 12 recommend_id,recommend_img_url,title,order_no, start_time FROM (SELECT ROW_NUMBER()OVER(PARTITION BY order_no ORDER BY start_time ASC) rowNum,* FROM info_latest_recommend_company_picture ilrcp WHERE ilrcp.calling_id='01' AND ilrcp.is_effect=1 and ilrcp.end_time>getdate()) temp WHERE temp.is_effect='1' AND DATEDIFF(dd,GETDATE(),end_time)>= 0 and temp.calling_id='01' ORDER BY temp.order_no ASC
此时结果记录如下:
注意,此处,order_no=2出现了两个,但是,在服务期限内,我们只能取有效的那个,那么该如何构造SQL,取出这条在服务期内有效的数据呢?考虑使用DISTINCT()函数消除重复行,但是,这样的话就获取不到有效广告信息之外的(失效,不在服务期)的广告信息。此时,考虑,使用ROW_NUMBER () OVER(PARTITION BY order_no ORDER BY START_Time ASC
SELECT ROW_NUMBER () OVER(PARTITION BY order_no ORDER BY START_Time ASC) rowNum,* FROM info_latest_recommend_company_picture ilrcp WHERE ilrcp.is_effect=1 and DATEDIFF(dd,GETDATE(),end_time)>= 0 AND ilrcp.calling_id='01'
这样就好办了,现在,我们只需要取出rowNum=1的数据就可以了
SELECT TOP 12 advert.* FROM ( SELECT ROW_NUMBER () OVER(PARTITION BY order_no ORDER BY START_Time ASC) rowNum,* FROM info_latest_recommend_company_picture ilrcp WHERE ilrcp.is_effect=1 and DATEDIFF(dd,GETDATE(),end_time)>= 0 AND ilrcp.calling_id='01' ) advert WHERE advert.rowNum=1 ORDER BY advert.order_no ASC
这样,变获取了我们需要的结果。
补充:ROW_NUMBER () OVER(PARTITION BY order_no ORDER BY START_Time ASC
简单的说row_number()从1开始,为每一条分组记录返回一个数字,这里的ROW_NUMBER() OVER (ORDER BY START_Time DESC) 是先把START_Time 列降序,再为降序以后的没条START_Time 记录返回一个序号。