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
try this:
UPDATE Table
SET x=x+1
where date in
(SELECT MIN(date)
FROM Table
group by id)
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)
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 ;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.