如何在Sql Server中使用动态生成的字段?

时间:2017-07-05 13:33:41

标签: mysql sql sql-server

我有一张叫做“Cart”的桌子。字段是:

  • CartId
  • ClientId
  • ProductId
  • Qty

现在我正在使用ProductMaster加入此表格以获取ProductNameProuctPrice

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。我怎么能这样做?

2 个答案:

答案 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;