明年mssql的总和金额

时间:2013-12-04 19:47:32

标签: sql sql-server sql-server-2012

我遇到一个查询问题。

我有这个订单表:

workerID orderID Year orderCount
274      869     2008   14
274      758     2006    2
274      770     2006   13
274      853     2006   10

我需要像这样创建一个表:

workerID orderID Year orderCount sumByYears
274      2005     30 (orderCount for year 2005)
274      2006    880 (orderCount for year 2005+2006)
274      2007   1456 (orderCount for year 2005+2006+2007)
274      2008    729 (...)

我很容易写这个查询:

SELECT workerID , Year , SUM(orderCount) 
FROM Orders
GROUP BY workerID , Year 
ORDER BY workerID , Year ;

但我不知道如何获得最后一栏。

3 个答案:

答案 0 :(得分:3)

假设你想要一个文字字符串这应该这样做:

SELECT workerID , Year , SUM(orderCount), '(orderCount for year' + Year + ')'
FROM Orders
GROUP BY workerID , Year 
ORDER BY workerID , Year ;

如果您真正追求的是按年计算的滚动总和,那么我相信这应该有效:

   SELECT workerID 
    , Year 
    , SUM(orderCount)
    , (SELECT SUM(orderCount)
        FROM Orders As runningORders
        WHERE runningOrders.Year <= Orders.Year         
    ) As SumByYears
FROM Orders
GROUP BY workerID , Year 
ORDER BY workerID , Year ;

以下是sqlfiddle

的示例

答案 1 :(得分:1)

您想要的通常称为跑步总数。在SQL Server 2012中,您可以使用SUM() OVER ()来计算它。

SELECT
  workerID,
  Year,
  orderCount = SUM(orderCount),
  sumByYears = SUM(SUM(orderCount)) OVER (PARTITION BY workerID ORDER BY Year) 
FROM Orders
GROUP BY workerID , Year 
ORDER BY workerID , Year ;

在此处阅读有关OVER子句的更多信息:

答案 2 :(得分:0)

试试这个:

SELECT workerID , Year , 
SUM(orderCount), '(orderCount for year' + Year + ')'
FROM Orders
GROUP BY workerID , Year 
ORDER BY workerID , Year ;