SQL two-Table update

Source: Internet
Author: User

Product (pid, name, amount, nowAmount): ID, name, existing quantity, current quantity
Trade (id, pid, operType, number): identifier, product identifier, operation type (warehouse receiving: 1, warehouse picking: 0), quantity

Test data in the Product table:

1 Apple 100 0
2 Orange 50 0

Test data in the Trade table:

1 1 1 432
2 1 0 50
3 2 1 20
4 2 0 40
5 1 1 30
6 2 0 20

An SQL statement is required to update the nowMount value in the Product table.
Statement: update p set p. nowAmount = p. amount + t. number
From Product as p, (select pid, sum (case operType when '0' then number * (-1) else number end) number
From Trade group by pid) as t where t. pid = s. pid

Or update p
Set p. nowAmount = t. number + p. amount
From Product as p
Inner join (select pid, sum (case operType when '0' then number * (-1) else number end) as number from Trade group by pid) as t
On p. pid = t. pid

After the two are executed in the same way, the Product table is:

1 Apple 100 512
2 Orange 50 10

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.