1

我有一个疑问;

select ProductID,  name, (unitPrice*quantity) As 'Stock Equity'
from tproduct
group by productID with rollup
;

我希望这返回一组行,最后一个是总计的计算,而不是重复最后一个结果?

谁能告诉我为什么以及如何克服这个问题?

这是目前的查询结果;

ProductID    Name           Stock Equity
1            cannon 600 D   3360
2            cannon 550 D   1000
3            cannon 500 D   750
4            cannon 5D      5000
5            cannon 650 D   9000
6            Nikon D5100    1000
7            Nikon D3200    420
8            Nikon D7000    2700
9            Nikon D800     6030
10           Nikon D90      4770
null         Nikon D90      4770
4

2 回答 2

1

您可以使用UNION ALL

select ProductID,  name, (unitPrice*quantity) As 'Stock Equity'
from tproduct
union all
select 'total', 'total', sum(unitPrice*quantity)
from tproduct

请参阅带有演示的 SQL Fiddle

或者你可以使用这样的东西:

select case when ProductID is null then 'total' else ProductId end Productid,  
  case when ProductID is null then 'total' else name end name, 
  sum(unitPrice*quantity) As 'Stock Equity'
from tproduct
group by ProductID with rollup

请参阅带有演示的 SQL Fiddle

于 2012-11-26T21:55:20.937 回答
0
select ProductID,  
       name, 
       (unitPrice*quantity) As 'Stock Equity',
       (select sum(unitPrice*quantity) from tproduct) As total
from tproduct
group by productID
于 2012-11-26T21:53:00.643 回答