根据来自另一个表的多个记录计算金额后更新表

时间:2019-03-18 18:01:05

标签: sql oracle

我有两个表,一个是Base_table,另一个是Txn_table,如下所示

Base_table

from Cython.Distutils.build_ext import new_build_ext as build_ext
# alternative:
# from distutils.command import build_ext

class my_build_ext(build_ext):
    """Workaround for rpath bug in distutils for OSX."""

    def finalize_options(self):
        super().finalize_options()
        # Special treatment of rpath in case of OSX, to work around python
        # distutils bug 36353. This constructs proper rpath arguments for clang.
        # See https://bugs.python.org/issue36353
        if sys.platform[:6] == "darwin":
            for path in self.rpath:
                for ext in self.extensions:
                    ext.extra_link_args.append("-Wl,-rpath," + path)
            self.rpath[:] = []

setup(
    cmdclass={'build_ext': my_build_ext}
    # ...
)

Txn_table

Person  | Amount
----------------
P1        300
p2        200   
p3        100

我需要基于 Txn_table 数据更新 Base_Table ,例如P1完成了借方和贷方操作,总计算结果类似于(贷方借方)=(400-200 )= 200,并且P1在 Base_table 中已经有300个,因此需要在 Base_Table 中更新P1的总值300 + 200 = 500。好吧,请帮助我编写 Oracle SQL 查询

更新后,Base_table中的数据应像这样。

Base_table

Person  |  txn_type  |  Amount
---------------------------------
P1        Debit         200    
P2        Credit        200    
P3        Debit         100    
P1        Credit        400

注意:在这里,我不应该只使用SQL查询来执行PLsql块更新。

3 个答案:

答案 0 :(得分:1)

内联相关子查询可能会完成工作:

UPDATE base_table b
SET b.amount =
    b.amount 
    + NVL(
        (SELECT SUM(DECODE(t.txn_type, 'Credit', 1, -1) * t.amount)
        FROM txn_table t
        WHERE t.person = b.person
    ), 0)

答案 1 :(得分:1)

在Oracle中,从一个表更新另一个表的典型方法是使用相关的子查询:

update base_table b
    set amount = b.amount +
                 (select sum(case when t.txn_type = 'Credit' then t.amount else - t.amount end)
                  from txn_table t
                  where t.person = b.person
                 )
    where exists (select 1
                  from txn_table t
                  where t.person = b.person
                  having sum(case when t.txn_type = 'Credit' then t.amount else - t.amount end) <> 0
                 );

答案 2 :(得分:0)

只是建议另一种方法。


class CustomViewCell: UITableViewCell {

@IBOutlet weak var imageView: UIImageView!

private var task: URLSessionDataTask?

override func prepareForReuse() {
    super.prepareForReuse()
    task?.cancel()
    imageView.image = nil
}

func configureWith(url string: String) {
    guard let url = URL(string: string) else { return }

    task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let data = data, let image = UIImage(data: data) {
            DispatchQueue.main.async {
                self.imageView.image = image
            }
        }
    }
    task?.resume()
 }
}