0

我想要一个 sql 查询结果如下:

LineNumber 单价 数量


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

请帮助我....

4

3 回答 3

3

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

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

于 2012-09-19T15:52:26.257 回答
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 ), ( ) ) 
于 2012-09-19T16:04:00.033 回答
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]
于 2012-09-19T15:53:16.573 回答