如何在SQL Server中查询此输出?

时间:2017-11-02 11:33:07

标签: sql-server-2008

我有这些数据:

NAME               AMOUNT              TYPE
-------------------------------------------
Apple               100                Good
Orange              200                Good
Apple               300                Good 
Orange              100               Damage

我需要这样的输出,Total Amount = SUM(Damage) - SUM(Good)

NAME          TOTAL AMOUNT 
--------------------------
Apple             400
Orange            100

2 个答案:

答案 0 :(得分:3)

Name   | Amount  |   Type
Apple  |  100    |   Good
Orange |  200    |   Good
Apple  |  300    |   Good
Orange |  100    |   Damage

SELECT t.Name as Name, SUM(t.Good) as Good, SUM(t.Damage) as Damage, SUM(t.Good) - SUM(t.Damage) as Total 
from (
    SELECT Name, SUM(Amount) as 'Good', 0 as 'Damage' 
    FROM `tb_name` 
    where Type = 'Good' group by Name 
 UNION 
    SELECT name, '0' as 'Good', SUM(Amount) as 'Damage' 
    FROM `tb_name` 
    where Type = 'Damage' group by Name) t 
    group by t.Name`;
  

输出

Name   | Good    |   Damage   |  Total
Apple  |  400    |   0        |  400
Orange |  200    |   100      |  100

答案 1 :(得分:0)

select FruitName, 
    (select ISNULL(sum(amount),0) 
        from Fruit d 
        where d.FruitName=m.FruitName and d.Type='Good')
     - (select ISNULL(sum(amount),0) 
        from Fruit d where d.FruitName=m.FruitName and d.Type='Damage') 
     as 'Total Amount' 
from Fruit m 
group by FruitName