Select one row per index value with max column value

后端 未结 3 917
死守一世寂寞
死守一世寂寞 2020-12-04 03:23

With a table setup with the following fields:

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

and housing thousands of rows here is e

相关标签:
3条回答
  • 2020-12-04 03:42

    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
    
    0 讨论(0)
  • 2020-12-04 03:44

    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

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题