表如下:
CREATE TABLE UserLog(uid TEXT, clicks INT, lang TEXT)
uid
字段应唯一。
以下是一些示例数据:
| uid | clicks | lang |
----------------------------------------
| "898187354" | 4 | "ru" |
| "898187354" | 4 | "ru" |
| "123456789" | 1 | <null> |
| "123456789" | 10 | "en" |
| "140922382" | 13 | <null> |
如您所见,我有多行,其中uid
字段现在已重复。我希望通过以下方式合并这些行:
clicks
字段被添加,如果lang
字段的先前值为null
,则更新它们。
对于上面显示的数据,它看起来像这样:
| uid | clicks | lang |
---------------------------------------
| "898187354" | 8 | "ru" |
| "123456789" | 11 | "en" |
| "140922382" | 13 | <null> |
似乎我可以找到很多方法来简单地删除重复的数据,而我并不一定要这样做。我不确定如何在执行此操作的SQL语句中引入逻辑。
答案 0 :(得分:1)
第一次更新:
update userlog
set
clicks = (select sum(u.clicks) from userlog u where u.uid = userlog.uid),
lang = (select max(u.lang) from userlog u where u.uid = userlog.uid)
where not exists (
select 1 from userlog u
where u.uid = userlog.uid and u.rowid < userlog.rowid
);
,然后删除不需要的重复行:
delete from userlog
where exists (
select 1 from userlog u
where u.uid = userlog.uid and u.rowid < userlog.rowid
);