SQL Update row with min Date of ID

2.8k views Asked by At

I have a Table with id,date,x

id         date         x
1  2015-06-09 12:20:45  1
1  2015-06-10 10:21:55  1
2  2015-06-08 12:34:12  1
2  2015-06-11 13:11:13  1
3  2015-06-07 14:50:44  1
3  2015-06-01 11:12:14  1

Now I want to increase x of the rows with the oldest date of each id. So I want this to come out:

id         date         x
1  2015-06-09 12:20:45  2
1  2015-06-10 10:21:55  1
2  2015-06-08 12:34:12  2
2  2015-06-11 13:11:13  1
3  2015-06-07 14:50:44  1
3  2015-06-01 11:12:14  2

That's how I tried:

UPDATE Table
SET x=x+1
where date=
(SELECT MIN(date)
FROM Table
WHERE id=??)

The ?? is where I don't know what to do. Moreover I get an error because I "can't specify target table for update in FROM clause". Maybe it's a completely wrong way, I hope someone can help me

3

There are 3 answers

0
Nikhil Batra On

try this:

UPDATE Table
SET x=x+1
where date in
(SELECT MIN(date)
FROM Table
group by id)
0
Dhaval On

Group by by ID get min date..

UPDATE Table
SET x=x+1
where date =
(SELECT top 1 MIN(date)
FROM Table
group by id)
0
Abhik Chakraborty On

You can do it using the JOIN and update as

update table_name t1
join(
  select id,min(date) as date from table_name
  group by id
)t2 on t1.id = t2.id and t1.date = t2.date
set t1.x = t1.x+1 ;

http://www.sqlfiddle.com/#!9/fec17/1