【问题标题】:Update columns with values from another column使用另一列的值更新列
【发布时间】:2014-11-25 12:16:14
【问题描述】:

我有一个 Sqlite 表,其中 ColumnA 中的行具有相同的值,但 ColumnB 中的值不同。下面的查询给了我几百行。

从 MyTable 中选择 ColumnA 按 Count(*) > 1 的 ColumnA 分组

我的要求是,对于具有相同 ColumnA 值的行,只要任何行的 ColumnC 中有值,就在所有行中填充 ColumnC 值。下面是输入和输出。

有人可以帮忙吗?

+--------------------------+
| +------+-------+------+  |
+--------------------------+
| |ColumnA|ColumnB|ColumnC |
| +------+-------+------+  |
| |C2     |Val1   |        |
| +------+-------+------+  |
| |C2     |Val2   |P       |
| +------+-------+------+  |
| |B2     |Val3   |Q       |
| +------+-------+------+  |
| |B2     |Val4   |        |
| +------+-------+------+  |
+--------------------------+

输出:

+---------------------------------------------------+
|              +------+-------+------+              |
+---------------------------------------------------+
| |ColumnA|ColumnB|ColumnC                          |
| +------+-------+------+                           |
| |C2     |Val1   |P        //add P to this row     |
| +------+-------+------+                           |
| |C2     |Val2   |P                                |
|                                                   |
| +------+-------+------+                           |
| |B2     |Val3   |Q                                |
| +------+-------+------+                           |
| |B2     |Val4   |Q          //add Q to this row   |
| +------+-------+------+                           |
+---------------------------------------------------+

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    这是你想要的吗?它使用相关子查询来更新值:

    update mytable
        set columnc = (select max(columnC) from mytable t2 where t2.columnA = mytable.columnA)
        where columnC is null;
    

    【讨论】:

    • 这正是我想要的。没有意识到 max(columnC) 即使对于文本列也可以做到这一点。非常感谢!
    猜你喜欢
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    相关资源
    最近更新 更多