具有where和group by的多行的SQL Server SUM

时间:2015-05-30 06:19:09

标签: sql sql-server tsql

我有一个SQL表格Details,其中列名为ITEMSTotalOrderCancelOrder

我写这样的查询

select Items, SUM(TotalOrder) as [TotalOrder], SUM(CancelOrder)as [CancelOrder] ,Source from Details group by Items

,结果似乎是这样的

  ITEMS        TotalOrder    CancelOrder 
  Laptop         102            5
  Desktop        9              1
  Tablet         17             0
  Tshirt         119            12
  TV             5              0

但我的列名Items包含数据LaptopDesktopTablet与名称Laptop相同,这就是我希望的原因获得像

这样的输出
  ITEMS        TotalOrder    CancelOrder 
  Laptop         128            6
  Tshirt         119            12
  TV             5              0

1 个答案:

答案 0 :(得分:0)

试试这个

select Items, SUM(TotalOrder) as [TotalOrder], SUM(CancelOrder)as [CancelOrder] 
from Details 
where Items NOT IN('Laptop','Desktop','Tablet')  group by Items 
UNION 
select 'Laptop',SUM(TotalOrder) as [TotalOrder], SUM(CancelOrder)as [CancelOrder] 
from Details 
where Items IN('Laptop','Desktop','Tablet')