Skip to content

Instantly share code, notes, and snippets.

@doshiraki
Created June 6, 2022 11:52
Show Gist options
  • Select an option

  • Save doshiraki/95f72a193cb6f774a313e1160c8a36d0 to your computer and use it in GitHub Desktop.

Select an option

Save doshiraki/95f72a193cb6f774a313e1160c8a36d0 to your computer and use it in GitHub Desktop.
DROP table testtbl
;
CREATE table
testtbl (id int,
dat datetime,
valuenum int,
valuenum2 int,
value varchar(30),
primary key(id,
dat))
;
;
insert into testtbl values(7, '1990-01-01', 2,-1, 'abc');
insert into testtbl values(7, '1990-01-02', 16,-1, 'abc');
insert into testtbl values(7, '1990-01-03', 3,-1, 'abc');
insert into testtbl values(8, '1990-01-03', 35,-1, 'abc');
insert into testtbl values(9, '1990-01-02', 7,-1, 'def');
insert into testtbl values(9, '1990-01-03', 1,-1, 'def');
insert into testtbl values(9, '1990-01-04', 4,-1, 'def');
;
SELECT *
FROM testtbl t
;
;
UPDATE
testtbl t
inner join (
SELECT
x.id,
MIN(x.dat) datsecond,
MAX(x.dat) datfirst
from
(
SELECT
cur.id,
cur.dat,
COUNT(nxt.id) rownum
from
testtbl cur
left join testtbl nxt
on
nxt.id = cur.id
and nxt.dat >= cur.dat
group by
cur.id,
cur.dat
) x
WHERE
x.rownum <= 2
group by
x.id
) tt
ON
tt.id = t.id
and tt.datfirst = t.dat
left join testtbl t2
on
tt.datfirst > tt.datsecond
and t2.id = tt.id
and t2.dat = tt.datsecond
set
t.valuenum2 = t.valuenum -
case
when t2.valuenum is null then 0
else
t2.valuenum -
case
when t.valuenum >= t2.valuenum then 0
else 100
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment