简体   繁体   English

sql update max(date) 分组依据

[英]sql update max(date) group by

  • raw data原始数据
no group团体 date日期 value价值 flag旗帜
1 1个 a一种 2022-10-13 2022-10-13 old老的 y
2 2个 a一种 2022-10-15 2022-10-15 new新的 y
3 3个 b b 2022-01-01 2022-01-01 old老的 n n
4 4个 b b 2022-01-03 2022-01-03 new新的 n n
  • step1.步骤1。 insert no1 raw插入 1 号原始
  • step2.第2步。 modify date value using by no2 raw使用 no2 raw 修改日期值

and I want to update latest date no1 raw using by no2 raw and the condition is where `flag` = "y"我想更新 no2 raw 使用的最新日期 no1 raw,条件是where `flag` = "y"

  • final sql table最终的sql表
no group团体 date日期 value价值 flag旗帜
1 1个 a一种 2022-10-15 2022-10-15 old老的 y
3 3个 b b 2022-01-01 2022-01-01 old老的 n n

is it possible?可能吗?

+) I insert/update raw data line by line. +) 我逐行插入/更新原始数据。

Not entirely clear but I hope below answer gives you a hint if not the solution.不完全清楚,但我希望下面的答案能给你一个提示,如果不是解决方案的话。

select  no,
       `group`,
        case when flag='Y' then mx_dt else `date` end as new_date,
        value,
        flag
from (    select no,
                 `group`,
                  value,
                  `date`,
                  flag ,
                  row_number() over(partition by `group` order by `date` asc ) as rn,
                  max(`date`) over (partition by `group`,(case when flag  <> 'Y' then `date`  end)   ) mx_dt
          from raw_data
    ) as tbl
where rn=1;

Above code will select the max(date) per group if the flag=Y otherwise it will take the date per row.如果标志=Y,上面的代码将选择每组的最大(日期),否则它将采用每行的日期。

https://dbfiddle.uk/JhRUti2h https://dbfiddle.uk/JhRUti2h

The solution is to self join the source table and select the right field, prioritizing the latest date.解决方案是自连接源表并选择正确的字段,优先考虑最新日期。

Here you have a working query:在这里你有一个工作查询:

WITH source_data AS (
SELECT 1 AS no_,  'a' AS group_, CAST('2022-10-13' AS DATE) AS date, 'old' AS value, 'y' AS flag
UNION ALL
SELECT 2, 'a', CAST('2022-10-15' AS DATE), 'new', 'y'
UNION ALL
SELECT 3, 'b', CAST('2022-01-01' AS DATE), 'old', 'n'
UNION ALL
SELECT 4, 'b', CAST('2022-01-03' AS DATE), 'new', 'n')

SELECT no_, group_, COALESCE(new_date, date), value, flag
FROM 
(SELECT * FROM source_data WHERE value = 'old') old_values
LEFT JOIN (SELECT group_ AS new_group, date AS new_date FROM source_data WHERE value = 'new' AND flag='y') new_values
ON old_values.group_ = new_values.new_group

The result is what you expected:结果如你所料:

no_ group_  f0_ value   flag
1   a   2022-10-15  old y
3   b   2022-01-01  old n

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

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