Select one row per index value with max column val

2019-01-12 11:44发布

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.

3条回答
三岁会撩人
2楼-- · 2019-01-12 12:00

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.

查看更多
Anthone
3楼-- · 2019-01-12 12:01

Have a look at GROUP BY and HAVING clauses.

select sku, max(eventstartdate)
FROM TABLE
group by sku
having eventstartdate <= sysdate

Edit: added HAVING statement

查看更多
闹够了就滚
4楼-- · 2019-01-12 12:07

other solution

 select distinct f3.* 
 from  yourtable f1
 inner join lateral
       (
        select * from yourtable f2
        where f1.SKU=f2.SKU
        order by EVENTSTARTDATE desc, EVENTENDDATE desc
        fetch first rows only
        ) f3 on 1=1
查看更多
登录 后发表回答