2012-11-26 82 views
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 

回答

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 with Demo

或者你可以用這樣的:

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 with Demo

+0

非常感謝這個作品完美:) – Matt

0
select ProductID, 
     name, 
     (unitPrice*quantity) As 'Stock Equity', 
     (select sum(unitPrice*quantity) from tproduct) As total 
from tproduct 
group by productID