[英]How do I set the value of a column be a result of a SQL query using one of the columns of the same table
[英]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.