sql query:所有行的总和并显示在列中

时间:2014-03-08 07:51:49

标签: sql-server

这是我的查询:

SELECT Name,
       Quantity,
       Price,
       (Quantity*Price)[Total Price] 
  FROM Menu,
       Items_per_Table,
       [735294] 
 WHERE Menu.Item_id = Items_per_Table.Item_id 
       AND [735294].OrderNo = Items_per_Table.OrderNo 
       AND Bill_Generated = 'True'

它返回:

Name                  Quantity   Price   Total Price
Aerated Drinks             1     30.00   30.00
Fresh Lime Soda/Water      3     60.00   180.00

在这里,我希望总价格的总和如下:另一列中30 + 180 = 210。 我该怎么做?

它应该回归:

Name                  Quantity   Price   Total Price    All Over Price
Aerated Drinks             1     30.00   30.00          30
Fresh Lime Soda/Water      3     60.00   180.00         210

2 个答案:

答案 0 :(得分:0)

对于SQL Server 2012,这应该可以满足您的需求;

SELECT Name,
       Quantity,
       Price,
       (Quantity*Price) [Total Price],
       SUM(Quantity*Price) OVER (ORDER BY menu.item_id) [All Over Price] 
  FROM Menu,
       Items_per_Table,
       [735294] 
 WHERE Menu.Item_id = Items_per_Table.Item_id 
       AND [735294].OrderNo = Items_per_Table.OrderNo 
       AND Bill_Generated = 'True'
ORDER BY menu.item_id

SUM(...) OVER (ORDER BY...)按照您提供的顺序执行运行总和。由于您的问题没有订单,我随意选择了menu.item_id来订购。

编辑:忘记添加SQLfiddle to test with

答案 1 :(得分:0)

尝试使用公用表表达式,(如果您使用的是SQL< SQl 2012)

;with cteabc
as (
SELECT Name,
       Quantity,
       Price,
       (Quantity*Price)[Total Price] 
  FROM Menu,
       Items_per_Table,
       [735294] 
 WHERE Menu.Item_id = Items_per_Table.Item_id 
       AND [735294].OrderNo = Items_per_Table.OrderNo 
       AND Bill_Generated = 'True'
    )
select
    t1.Name,
    t1.Quantity,
    t1.Price,
    rt.runningTotal
from cteabc t1
 cross apply (select sum([Total Price]) as runningTotal
                from cteabc t2
                where  t2.rn<= t1.rn
            ) as rt
order by t1.Name

<强> SQL Fiddle