我正在尝试使用group by子句根据列 'last' 更新dt列。我需要通过hid,tid,tdate,fid,did,depid,acc 找到群组' 群组的最后日期“并设置 'dt'< / em> 此组中所有记录的值。
例如:
| id | hid | tid | tdate | fid | did | p2 | depid | acc | dt | last |
|----------|-------|-----|------------|-----|-----|-------|-------|------|------|----------------------|
| 3742030 | 12332 | 1 | 2017-09-02 | 1 | 1 | 9560 | 1 | 5334 | 1 | 2016-11-03T09:00:20Z |
| 3799297 | 2386 | 1 | 2017-08-29 | 1 | 1 | 8480 | 1 | 5352 | 1 | 2016-11-03T11:12:55Z |
| 4848877 | 2386 | 1 | 2017-08-29 | 1 | 1 | 8720 | 1 | 5352 | 2369 | 2016-12-17T16:59:22Z |
| 10706343 | 12332 | 1 | 2017-09-02 | 1 | 1 | 9660 | 1 | 5334 | 2065 | 2017-03-01T12:32:27Z |
| 14546682 | 2386 | 1 | 2017-08-29 | 1 | 1 | 11720 | 1 | 5352 | 4431 | 2017-05-12T10:24:09Z |
| 15824920 | 12332 | 1 | 2017-09-02 | 1 | 1 | 10820 | 1 | 5334 | 1111 | 2017-07-15T05:19:04Z |
到
| id | hid | tid | tdate | fid | did | p2 | depid | acc | dt | last |
|----------|-------|-----|------------|-----|-----|-------|-------|------|------|----------------------|
| 3742030 | 12332 | 1 | 2017-09-02 | 1 | 1 | 9560 | 1 | 5334 | 1111 | 2016-11-03T09:00:20Z |
| 3799297 | 2386 | 1 | 2017-08-29 | 1 | 1 | 8480 | 1 | 5352 | 4431 | 2016-11-03T11:12:55Z |
| 4848877 | 2386 | 1 | 2017-08-29 | 1 | 1 | 8720 | 1 | 5352 | 4431 | 2016-12-17T16:59:22Z |
| 10706343 | 12332 | 1 | 2017-09-02 | 1 | 1 | 9660 | 1 | 5334 | 1111 | 2017-03-01T12:32:27Z |
| 14546682 | 2386 | 1 | 2017-08-29 | 1 | 1 | 11720 | 1 | 5352 | 4431 | 2017-05-12T10:24:09Z |
| 15824920 | 12332 | 1 | 2017-09-02 | 1 | 1 | 10820 | 1 | 5334 | 1111 | 2017-07-15T05:19:04Z |
架构: http://sqlfiddle.com/#!9/4fad1d/1
是否有某种方法可以根据组更新表中的所有行?
由于
答案 0 :(得分:1)
使用子查询加入表,该子查询将找到每个组的最新行。
update of t
join (
select t1.*
from of t1
join (
select hid,tid,tdate,fid,did,depid,acc, max(last) as last
from of
group by hid,tid,tdate,fid,did,depid,acc
) t2 using (hid,tid,tdate,fid,did,depid,acc,last)
) t3 using (hid,tid,tdate,fid,did,depid,acc)
set t.dt = t3.dt;
http://sqlfiddle.com/#!9/93708/2
对于子查询中的连接,您还可以使用NATURAL JOIN
natural join (
select hid,tid,tdate,fid,did,depid,acc, max(last) as last
from of
group by hid,tid,tdate,fid,did,depid,acc
) t2