简体   繁体   中英

How to do a subtraction in a stored procedure in SQL Server 2008 R2

I am a beginner when it comes to stored procedures, the database of my job is SQL Server 2008 R2 and I don't know how to do a simple subtraction of two values.

For example:

Excel table:

在此处输入图片说明

In this table, the third column is equal to the subtraction of the first column and the second column

On the column of a table of my database, the first and the second columns are in one column:

Table:

在此处输入图片说明

So, the third column should be the difference between the first and the second column, but I need to calculate the subtraction of the two values, I can bind the values with the article, that have the same number.

How can I do this in a stored procedure? I don't know how to do that, doing a While, declaring variables, all of that.

Any help will be really grateful, Thanks.

Select Articulo
      ,Col1     = sum(case when Cantidad>0 then Cantidad else 0 end)
      ,Col2     = sum(case when Cantidad<0 then Cantidad else 0 end)*-1
      ,Col3     = sum(Cantidad)*-1
 From  YourTable
 Group By Articulo

Returns

Articulo    Col1    Col2    Col3
1003        64000   338464  274464
1004        43200   271921  228721
3002        8411    11082   2671
3007        57600   57238   -362

You need to use a full self join

 Select p.canditad Positive, -n.canditad Negative, 
    p.canditad+n.canditad Difference
 From table p          -- <-- p for positive values
    full join table n  -- <-- n for negative values
       on n.articulo = p.articulo 
          and p.canditad > 0
          and n.canditad < 0

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