简体   繁体   中英

Distinct subjects, Sum and group by

i have a situation with a table like this:

----------------------------------------------
|   id   |  subject |    type    |   value   |
==============================================
|   1    |  AAA     |     IN     |   900.00  |
|   2    |  BBB     |     IN     |   200.00  | 
|   3    |  BBB     |     OUT    |   140.00  | 
|   4    |  AAA     |     OUT    |   650.00  | 
|   5    |  BBB     |     IN     |    90.00  | 
|   6    |  CCC     |     OUT    |   50.80   | 
|   7    |  AAA     |     OUT    |   480.40  | 
|   8    |  CCC     |     IN     |   645.20  |
|   9    |  CCC     |     OUT    |   111.80  |
|--------|----------|------------|-----------|

and i need to sum all values based on their type and show the results for each subject so the desired result must be:

----------------------------------------
|  subject | income(IN) | outcome(OUT) |
========================================
|  AAA     |   900.00   |    1130.40   |
|  BBB     |   290.00   |     140.00   |
|  CCC     |   645.20   |     162.60   |

where the income(IN) column shows the sums of each subject where type is IN and the same does the column: outcome(OUT). I have try several query but without success.

Would be nice your help. Thanks in advance.

You can use conditional aggregation using Case..When expression with Group By clause:

SELECT
  subject, 
  SUM(CASE WHEN type = 'IN' THEN value END) AS income, 
  SUM(CASE WHEN type = 'OUT' THEN value END) AS outcome 
FROM your_table 
GROUP BY subject

EDIT:

It seems from comments that datatype of the value column is not numeric. It is string, with possible commas in it (due to number formatting). We will need to use Replace() function to replace the commas with empty string. And, then use Cast() to convert it into numeric value.

SELECT
  subject, 
  SUM(CASE WHEN type = 'IN' 
           THEN CAST(REPLACE(value, ',', '') AS DECIMAL(11,2)) 
      END) AS income, 
  SUM(CASE WHEN type = 'OUT' 
           THEN CAST(REPLACE(value, ',', '') AS DECIMAL(11,2)) 
      END) AS outcome 
FROM your_table 
GROUP BY subject

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