我有一张叫做“Cart”的桌子。字段是:
CartId
ClientId
ProductId
Qty
现在我正在使用ProductMaster
加入此表格以获取ProductName
和ProuctPrice
select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
(pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
inner join ProductMaster as pm on cc.ProductId = pm.ProductId
现在我想使用动态字段GrandTotal
生成SubTotal
。我怎么能这样做?
答案 0 :(得分:0)
with CTE as
(
select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
(pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
inner join ProductMaster as pm on cc.ProductId = pm.ProductId
where cc.ClientId = @id
)
select *
from CTE
union
select null,null, null,null, sum(SubTotal) -- this is a grand total of all sub totals
from CTE
这不是正确的Rollup方法,但也不是你的,所以这样可以正常工作
答案 1 :(得分:0)
试试这个:
select subtable.CartId, sum(subtable.SubTotal)
from (
select cc.CartId,cc.ProductId,pm.ProductName,cc.Qty,
(pm.ProductPrice * cc.Qty) As SubTotal
from ClientCart as cc
inner join ProductMaster as pm on cc.ProductId = pm.ProductId
where cc.ClientId = @id ) subtable
group by subtable.CartId;