繁体   English   中英

使用组中第一行的数据更新组中的最后一行

[英]Update last row in group with data from first row in group

我目前正在将数据从一种结构转换为另一种结构,并且在此过程中,我必须从组中的第一个条目获取状态ID,并将其应用于该组中的最后一个条目。 使用硬编码值时,我可以定位并更新组中的最后一个项目,但是尝试使用第一个条目中的status_id时,我遇到了麻烦。 这是数据结构的示例。

-----------------------------------------------------------
| id | ticket_id | status_id | new_status_id | created_at |
-----------------------------------------------------------
| 1  | 10        | NULL      | 3             | 2018-06-20 |
| 2  | 10        | 1         | 1             | 2018-06-22 |
| 3  | 10        | 1         | 1             | 2018-06-23 |
| 4  | 10        | 1         | 1             | 2018-06-26 |
-----------------------------------------------------------

因此,想法是采用ID 1的new_status_id并将其应用于ID 4的相同字段。

这是使用硬编码值时有效的查询

UPDATE Communications_History as ch
    JOIN
    ( 
        SELECT communication_id, MAX(created_at) max_time, new_status_id
        FROM Communications_History
        GROUP BY communication_id
    ) ch2 
    ON ch.communication_id = ch2.communication_id AND ch.created_at = ch2.max_time
SET ch.new_status_id = 3

但是,当我使用以下查询时,我Unknown column ch.communication_id in where clause获得Unknown column ch.communication_id in where clause

UPDATE Communications_History as ch
    JOIN
    ( 
        SELECT communication_id, MAX(created_at) max_time, new_status_id
        FROM Communications_History
        GROUP BY communication_id
    ) ch2 
    ON ch.communication_id = ch2.communication_id AND ch.created_at = ch2.max_time
SET ch.new_status_id = (
    SELECT nsi FROM 
    (
        SELECT new_status_id FROM Communications_History WHERE communication_id = ch.communication_id AND status_id IS NULL
    ) as ch3
)

谢谢!

所以我只是想出了 使用变量 原来的“解决方案”只有在表中有一张票证的历史记录时才有效,但是当所有数据都导入后,它就不再起作用。 但是,此调整似乎可以解决该问题。

UPDATE Communications_History as ch
    JOIN
    ( 
        SELECT communication_id, MAX(created_at) max_time, new_status_id
        FROM Communications_History
        GROUP BY communication_id
    ) ch2 
    ON ch.communication_id = ch2.communication_id AND ch.created_at = ch2.max_time
SET ch.new_status_id = ch2.new_status_id;

暂无
暂无

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

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