SQL simple difference (subtraction, inventory) Calculation

Source: Internet
Author: User

A few days ago, the inventory should be displayed when the school made a product release. The inventory is calculated by the difference between the incoming and outgoing goods. The main fields in the record table of incoming goods are as follows: PID is the product ID, num is the quantity, state is the status, and 0 is the incoming value, 1 is output.

PID num state1 100 02 50 03 150 02 5 11 10 1

SQL Implementation Method

Select PID, sum (case state when 0 then num else-num end) as num from recordgroup by PID

To connect to the product table, obtain the product name.

PID pname1 small A2 small B3 small C

Cascade

 

Select max (pname), record. PID, sum (case state when 0 then num else-num end) as num from record inner join product on record. PID = product. pidgroup by record. PID

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.