Saturday, 15 September 2012

sql server - How to sum positive and negative values -


I wrote a question for the outcome of the results, now with that result, from the positive values ​​on the basis of some other columns Negative values ​​have to be reduced.

My query:

  Select ISNULL (SUM (QTYH), 0) as QTY, ISNULL (SUM (AMTH), 0 ) as in AMT, PART_NBR, A_NBR, the DATE (Select PART_NBR, R.A_NBR, episode when PO_DEBIT_CREDIT = 'H' then - QTY ends as other QTYH the case when PO_DEBIT_CREDIT = 'H' is AMT AMT end AMTP, DATEPART Yyyy, R.DATE) as DATE, receipt of Pio_debiai Credit Master M as R, sellers as T WHERE R.A_NBR = 'a-10' and CAST (DATEPART (Yyyy, R.DATE) as varchar) & gt; = '2013' and CAST (as of DATEPART (yyyy, R.DATE) varchar) & lt; = '2013' and Ar.a_anbiar = Peepiananbiar by M.a_ Anbiar Group, Ara_anbiar, DATEPART (yyyy, R.DATE), PO_DEBIT_CREDIT, QTY, AMT) TB PART_NBR as one group, A_NBR, DATE, PO_DEBIT_CREDIT  

Result:

  QTY AMT PART_NBR A_NBR Date = ================= =================== -1-11208.58 101A-10 2013 8 89668.64 101A-10 2013 3 46362.42 102A-10 2013  

I want to group rows based on the last 3 column: PART_NBR, A_NBR, date , and there are values ​​of the first 2 columns that were added together on the basis of that grouping.

desired output :

  QTY AMT PART_NBR A_NBR dated 7 78,460.06 101-A-10 2013 3 46362.42 102 A -10 2013   

Wrap your query in a subview and add some grouping and aggregation to it:

  SELECT SUM (QTY) AS QTY, SUM (AMT) AS AMT, PART_NBR, A_NBR, from [date] (select ... your current question is here) PPNNBR, A_NBR, [date]   

will group it from the previous 3 columns: PART_NBR, A_NBR, [date] and the first 2 columns per group Add values, thus adding positive values ​​is negative value.

Here is the result of a query that takes your query out of the output, wrapped in a subquery:

  create table # your site ([ktee] int, [ AMT] Decimal (10, 2), [PPNNBR] int, [A_NBR] Vartcha (4), [date] int; INSERT #YourSubquery ([QTY], [AMT], [PART_NBR], [A_NBR], [date]) value (-1, -11,208.58, 101, "A-10", 2013), (8, 89,668.64, 101) , 'A-10', 2013), (3, 46362.42, 102, 'A-10', 2013); Piapiananbiar, A_anbiar, [date] drop Growth # your Sabari   SEUM SUM (QTY) AS QTY, SUM (AMT) AS AMT, PART_NBR, A_NBR, [date] from (SELECT * FROM # YourSubquery) Ex> 

Output:

QTY AMT PART_NBR A_NBR Date =================== ====================== 78460.06 101-A-10 2013 3 46362.42 102A-10 2013

Warning : This is based on your assumption that your AMT column is a numeric data type, because your output is showing $ sign.


No comments:

Post a Comment