每个索引值选择一行,最大列值 [英] Select one row per index value with max column value

查看:22
本文介绍了每个索引值选择一行,最大列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用具有以下字段的表格设置:

SKU, EVENTSTARTDATE, EVENTENDDATE, PRICE, (...etc...)

此处包含数千行是示例数据(日期为 YYMMDD,不包括世纪代码):

<上一页>1111111、101224、101231、10.991111111、110208、110220、9.991111111、110301、110331、8.992222222、101112、101128、15.992222222、101201、110102、14.99等等

我想让一个 SELECT 语句为每个 SKU 返回一行,其中最大 EVENTSTARTDATE 没有 WHERE 子句隔离特定 SKU 或不完整的 SKU 子集(所需的 SELECT 语句应为所有 SKU 每个 SKU 返回一行).我最终想添加开始日期小于或等于当前日期,结束日期大于或等于当前日期的条件,但我必须先从某个地方开始.

所需的示例结果(现在只是最大日期):

<上一页>1111111、110301、110331、8.992222222、101201、110102、14.99等等.

解决方案

从最近的DB2版本,可以使用解析函数ROW_NUMBER()

选择 *从 (选择表名.*,ROW_NUMBER() OVER(按 sku 分区ORDER BY eventstartdate DESC) 作为 RowNumFROM 表名)X其中 X.RowNum=1

对于每个分区(SKU 组),数据按照 order by eventstartdate desc 的行编号,因此 1,2,3,...从 1 开始表示最新的 EventStartDate.然后,WHERE 子句仅获取每个 SKU 的最新信息.

With a table setup with the following fields:

SKU, EVENTSTARTDATE, EVENTENDDATE, PRICE, (...etc...)

and housing thousands of rows here is example data (dates are YYMMDD, century code excluded):

1111111, 101224, 101231, 10.99
1111111, 110208, 110220, 9.99
1111111, 110301, 110331, 8.99
2222222, 101112, 101128, 15.99
2222222, 101201, 110102, 14.99
etc

I'd like to have a SELECT statement return one row per SKU with the maximum EVENTSTARTDATE without having a WHERE clause isolating a specific SKU or incomplete subset of SKUs (desired SELECT statement should return one row per SKU for all SKUs). I'd eventually like to add the criteria that start date is less than or equal to current date, and end date is greater than or equal to current date, but I have to start somewhere first.

Example results desired (for now just max date):

1111111, 110301, 110331, 8.99
2222222, 101201, 110102, 14.99
etc.

解决方案

From recent versions of DB2, you can use the analytical function ROW_NUMBER()

SELECT * 
FROM (
    SELECT 
        tablename.*, 
        ROW_NUMBER() OVER (PARTITION BY sku 
                           ORDER BY eventstartdate DESC) As RowNum
        FROM tablename) X 
WHERE X.RowNum=1

For each Partition (group of SKU), the data is row numbered following the order by eventstartdate desc, so 1,2,3,...starting from 1 for the latest EventStartDate. The WHERE clause then picks up only the latest per SKU.

这篇关于每个索引值选择一行,最大列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆