一个SQL查询,用于列的所有值的总和

时间:2012-09-19 15:50:56

标签: sql-server

我希望sql查询结果如下:

LineNumber UnitPrice Quantity


  1                14               12      
  2                09               10      
  3                34                5       
  4                18                9      
  5                42               40       
  6                07               10      
  7                45               15    
                                   -----   
                                   101

请帮助我....

3 个答案:

答案 0 :(得分:3)

另一种方式

WITH YourTable(LineNumber, UnitPrice, Quantity)
     AS (SELECT 1, 14,12
         UNION ALL
         SELECT 2, 09, 10
         UNION ALL
         SELECT 3, 34, 5
         UNION ALL
         SELECT 4, 18, 9
         UNION ALL
         SELECT 5, 42, 40
         UNION ALL
         SELECT 6, 07, 10
         UNION ALL
         SELECT 7, 45, 15)
SELECT LineNumber,
       UnitPrice,
       SUM(Quantity) AS Quantity
FROM   YourTable
GROUP  BY GROUPING SETS ( ( LineNumber, UnitPrice, Quantity ), ( ) ) 

答案 1 :(得分:2)

要获得总数,您将使用聚合:

select sum(quantity) Total
from yourtable

要从表中返回数据:

select LineNumber, UnitPrice, Quantity
from yourTable

要将它们一起归还,您可以使用UNION ALL

select LineNumber, UnitPrice, Quantity
from yourTable
UNION ALL
select 0, 0, sum(quantity) Total
from yourtable

请参阅SQL Fiddle with Demo

答案 2 :(得分:1)

-- For all the data from the table
SELECT [LineNumber], [UnitPrice], [Quantity] FROM [SomeTable]

-- For the sum of the quantity field.
SELECT SUM([Quantity]) AS [Sum] FROM [SomeTable]