问题描述
使用以下字段设置表格:
SKU,EVENTSTARTDATE,EVENTENDDATE,PRICE, ..)
并且此处包含数千行是示例数据(日期为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
等
,您可以使用分析函数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
对于每个分区(SKU组),数据按 order by eventstartdate desc ,所以1,2,3,...从最新的EventStartDate的1开始。 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 etcI'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=1For 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.
这篇关于使用最大列值为每个索引值选择一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!