选择具有最大列值的每个索引值一行
通过具有以下字段的表设置:
SKU, EVENTSTARTDATE, EVENTENDDATE, PRICE, (...etc...)
并容纳数千行,这里是示例数据(日期为 YYMMDD,世纪代码除外):
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
我希望有一个 SELECT 语句为每个 SKU 返回一行,其中最大 EVENTSTARTDATE 没有 WHERE子句隔离特定 SKU 或不完整的 SKU 子集(所需的 SELECT 语句应为所有 SKU 的每个 SKU 返回一行)。我最终想添加开始日期小于或等于当前日期和结束日期大于或等于当前日期的标准,但我必须先从某个地方开始。
所需的示例结果(目前只是最大日期):
1111111, 110301, 110331, 8.99 2222222, 101201, 110102, 14.99 etc.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从最新版本的 DB2 开始,您可以使用分析函数 ROW_NUMBER()
对于每个分区(SKU 组),数据按照
order by eventstartdate desc
进行行编号,因此 1,2,3, ...最新的 EventStartDate 从 1 开始。然后,WHERE 子句仅选取每个 SKU 的最新版本。From recent versions of DB2, you can use the analytical function ROW_NUMBER()
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.查看 GROUP BY 和 HAVING 子句。
编辑:添加 HAVING 语句
Have a look at GROUP BY and HAVING clauses.
Edit: added HAVING statement
其他解决方案
other solution