简体   繁体   中英

SQL Server: subtract or sum between rows in the same column then update the results

I have a table my MS SQL Server, which has a standard row type BID . I want to subtract all the row type ASK from BID in column availableAmount then update the result into the BID row at the same column. At the same time, I want to calculate the sum of fulfilledAmount of row type ASK then update the result into the same column of row type BID . I'm still learning SQL but is it possible to do this complicate process?

EDIT

Example:

Before execution:

id   | type | availableAmount | fulfilledAmount | 
-----+------+-----------------+-----------------+
abcv | ASK  | 500             | 500             | 
xyzs | ASK  | 600             | 600             | 
scwd | BID  | 10000           | 0               | 
cd21 | ASK  | 1300            | 1300            |
sadc | ASK  | 3400            | 3400            |
2w3e | ASK  | 2500            | 2500            |  

After execution:

id   | type | availableAmount | fulfilledAmount | 
-----+------+-----------------+-----------------+
abcv | ASK  | 500             | 500             | 
xyzs | ASK  | 600             | 600             | 
scwd | BID  | 1700            | 8300            | 
cd21 | ASK  | 1300            | 1300            |
sadc | ASK  | 3400            | 3400            |
2w3e | ASK  | 2500            | 2500            |  

If I understood correct, you need something in the line of:

UPDATE myTable
SET availableAmount = availableAmount - (
        SELECT SUM(availableAmount)
        FROM myTable
        WHERE TYPE = 'ASK'
        )
    ,fulfilledAmount = (
        SELECT SUM(fulfilledAmount)
        FROM myTable
        WHERE TYPE = 'ASK'
        )
WHERE TYPE = 'BID'
AND ID ='scwd'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM