Matt
Matt

Reputation: 361

Adding a total row

I have a query;

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

I wish for this to return a set of rows with the last being a calculation of the Total, instead its repeating the last result?

can anyone tell me why and how to overcome this please?

this is the query result at the moment;

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

Upvotes: 1

Views: 60

Answers (2)

Taryn
Taryn

Reputation: 247680

You can use UNION ALL:

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

See SQL Fiddle with Demo

Or you can use something like this:

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

See SQL Fiddle with Demo

Upvotes: 1

juergen d
juergen d

Reputation: 204766

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

Upvotes: 0

Related Questions