SQL:使用SUM和COUNT函数的结果异常

时间:2019-01-05 13:25:50

标签: sql-server tsql

考虑到“无限制的前导和当前行之间的范围”的概念,我使用了代码中所见的SUM和COUNT函数,如果您查看我的结果,在TotalSalary下,我希望第一行为1000,第二行似乎是正确的,即1000 + 1000 = 2000,第三行又是不正确的,即1000 + 1000 + 2000应该是4000,但它是6000,这是您的想法,类似地,计数似乎也给出了错误的结果,我希望, 1,2,3,4,5,6 ..

DECLARE @Employees TABLE
(   EmpId INT Identity(1,1) NOT NULL, 
    EmpName VARCHAR(50) NULL,
    EmpGender VARCHAR(10),
    EmpSalary INT
);

INSERT INTO @Employees VALUES ('Rehan','Male', 2000 );
INSERT INTO @Employees VALUES ('Rohan','Male', 3000 );
INSERT INTO @Employees VALUES ('Donna','Female', 2500 );
INSERT INTO @Employees VALUES ('Mark','Male', 1000);
INSERT INTO @Employees VALUES ('Aarav','Female', 1000);
INSERT INTO @Employees VALUES ('Nick','Male', 2000);

SELECT 
    EmpId, EmpName, EmpGender, EmpSalary
    , SUM(EmpSalary) OVER (ORDER BY EmpSalary) 'TotalSalary'
    , COUNT(EmpSalary) OVER (ORDER BY EmpSalary) 'Count'
FROM @Employees;

Results

1 个答案:

答案 0 :(得分:2)

您需要添加ROWS UNBOUNDED PRECEDING,默认值为RANGE

所以

SELECT 
    EmpId, EmpName, EmpGender, EmpSalary
    , SUM(EmpSalary) OVER (ORDER BY EmpSalary ROWS UNBOUNDED PRECEDING) 'TotalSalary'
    , COUNT(EmpSalary) OVER (ORDER BY EmpSalary ROWS UNBOUNDED PRECEDING) 'Count'
FROM @Employees;

返回类似

+-------+---------+-----------+-----------+-------------+-------+
| EmpId | EmpName | EmpGender | EmpSalary | TotalSalary | Count |
+-------+---------+-----------+-----------+-------------+-------+
|     4 | Mark    | Male      |      1000 |        1000 |     1 |
|     5 | Aarav   | Female    |      1000 |        2000 |     2 |
|     6 | Nick    | Male      |      2000 |        4000 |     3 |
|     1 | Rehan   | Male      |      2000 |        6000 |     4 |
|     3 | Donna   | Female    |      2500 |        8500 |     5 |
|     2 | Rohan   | Male      |      3000 |       11500 |     6 |
+-------+---------+-----------+-----------+-------------+-------+

在绑定EmpSalary的情况下,哪一行排在第一位是任意的

This article关于ROWSRANGE

的更多详细信息