繁体   English   中英

如何使用sql select通过一组记录中的一列获取最大值的结果?

[英]How using sql select get result with max value by one columns in a set of records?

我在表中有这些数据。

date       | name        | code
2020-01-01 | category1   | 0
2020-01-02 | category1   | 1
2020-01-03 | category1   | 2
2020-01-04 | category1   | 3
2020-01-05 | category1   | 0
2020-01-06 | category1   | 1
2020-01-07 | category1   | 2
2020-01-08 | category1   | 0
2020-01-01 | category2   | 0
2020-01-02 | category2   | 0
2020-01-03 | category2   | 1
2020-01-04 | category2   | 0
2020-01-05 | category2   | 1
2020-01-06 | category2   | 2
2020-01-07 | category2   | 0
2020-01-08 | category2   | 1
......

集合中的列码加1。

需要获取一组记录中一列具有最大值的记录。 我的例子的结果必须是:

date       | name        | code
2020-01-04 | category1   | 3
2020-01-07 | category1   | 2
2020-01-03 | category2   | 1
2020-01-06 | category2   | 2
2020-01-08 | category2   | 1
......

这是你想要的吗?

select date, name, code
from (
    select 
        t.*,
        lead(code) over(partition by name order by date) lead_code
    from mytable t
) t 
where not code <= lead_code

对于您的示例数据, 这会产生

date       | name      | code
:--------- | :-------- | ---:
2020-01-04 | category1 |    3
2020-01-07 | category1 |    2
2020-01-03 | category2 |    1
2020-01-06 | category2 |    2
WITH cte AS (
SELECT date, 
       name, 
       code, 
       LEAD(code) OVER (PARTITION BY name ORDER BY date) next_code,
       LEAD(name) OVER (PARTITION BY name ORDER BY date) next_name
FROM source_table
)
SELECT date, name, code
FROM cte
WHERE (    name = next_name 
        OR next_name IS NULL )
  AND (    code > next_code
        OR next_code IS NULL )  
  AND code > 0;

小提琴

附注。 感谢GMB - 从他的回答中窃取了小提琴的基础。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM