【问题标题】:Update one column as sum of other two columns将一列更新为其他两列的总和
【发布时间】:2012-03-02 02:17:25
【问题描述】:

我需要更新表的每一行,其中一列作为同一个表中其他两列的总和

类似的东西

UPDATE table1 SET table1.column1 = sum (table1.column1 + table1.column2) 每一行

我试过了

This is working for me

UPDATE table1 SET column1 =(SELECT  SUM(column1 + column2)  FROM table1 where rowid = 1) WHERE rowid = 1

所以我可以通过首先选择所有 rowId 来迭代每个 rowid 来做到这一点

for( all rowid as i){
    UPDATE table1 SET column1 =(SELECT  SUM(column1 + column2)  FROM table1 where rowid = i) WHERE rowid = i
    }

但我需要在一个查询中处理该表中的所有行

当我尝试时:

update table1  set column1  = (select (column1  + column2) from table1 )

这将汇总 column1 和 column2 的所有值 我想做一行

有什么想法吗?

我在 sqlite for Android 中工作

【问题讨论】:

    标签: android sql sqlite


    【解决方案1】:

    不需要循环或内部选择。试试这个:

    UPDATE table1 SET column1 = column1 + column2
    

    【讨论】:

    • 我也有类似的问题。你用了什么方法?使用 rawQuery 它不起作用。使用 execSQL 它可以工作(对我来说),但文档说:“执行一个不是 SELECT/INSERT/UPDATE/DELETE 的单个 SQL 语句。”
    • 如何使用 ContentValues 做同样的事情?而不是 SQL
    【解决方案2】:

    允许从set 子句中的列中读取:

    UPDATE  table1 
    SET     column1 = column1 + column2
    WHERE   rowid = 1
    

    【讨论】:

      【解决方案3】:

      对于你不需要WHERE谓词的所有行:

      UPDATE table SET
        column1 = column1+column2
      

      仅此而已。

      【讨论】:

        【解决方案4】:

        我发现一个 cte 最适合我

        ;with new_count
        as
        (select rownumber
            ,sum(isnull([col1],0) + 
            isnull([col2],0) + 
            isnull([col3],0) + 
            isnull([col4],0) + 
            isnull([col5],0)) as [New Count]
            from #tbl1
            group by rownumber
        )
        update t1
            set t1.[New Count] = isnull(nc.[New Count],0)
            from new_count nc
            join #tbl1 t1
            on t1.rownumber = nc.rownumber
        

        【讨论】:

        • 您能解释一下这个解决方案的作用吗?这将对正在阅读它的其他人有所帮助。
        猜你喜欢
        • 1970-01-01
        • 2017-09-03
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        • 1970-01-01
        • 2022-10-18
        • 2021-10-05
        • 1970-01-01
        相关资源
        最近更新 更多