每月总结SQL

时间:2017-09-12 21:29:29

标签: sql sql-server sum

我正在尝试在SQL服务器中创建每日数字和月份总数。

    DATE                             Name         Figure             MTD
    2017-09-01 00:00:00.000          Luke          10              0.000000
    2017-09-02 00:00:00.000          Luke          10              0.000000
    2017-09-03 00:00:00.000          Luke          10              0.000000
    2017-09-04 00:00:00.000          Luke          10              0.000000

基本上我希望mtd显示40,即使我限制在下面只有一天。

    DATE                     Name               Figure              MTD
    2017-09-01 00:00:00.000 Luke                  10                40

我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:4)

MS Sql Server中的示例代码如下:

 CREATE TABLE #Order(ORDERDATE datetime,SalespersonName VARCHAR(30),  DailyFigure int)

INSERT INTO #Order VALUES
    ('2017-09-01 00:00:00.000','Luke',10),              
    ('2017-09-02 00:00:00.000','Luke',10),              
    ('2017-09-03 00:00:00.000','Luke',10),              
    ('2017-09-04 00:00:00.000','Luke',10);   

    SELECT * FROM #Order 

    SELECT * FROM 
    (SELECT ORDERDATE, SalespersonName,DailyFigure, SUM(DailyFigure) OVER(PARTITION BY SalesPersonName, MONTH(OrderDate)) AS MTD
    FROM #Order) as r
    WHERE ORDERDATE = '2017-09-01 00:00:00.000'

答案 1 :(得分:0)

 SELECT MIN(ORDERDATE), 
        SalespersonName,
        AVG(DailyFigure) DailyFigure,
        SUM(DailyFigure) MTD
   FROM Order