如何编写单个 SQL 查询以获取 SQL Server 2008 中其他列的列聚合?
How to write a single SQL query to get aggregate of column as other column in SQL Server 2008?
我有一个 table Employee
.
如何获取 table 的聚合列作为单独的列,如图所示?
我去年遇到的确切问题。希望对您有所帮助。
SELECT e1.EmpId,
e1.EmpName
e1.EmpSalary,
SUM(e2.EmpSalary) AS Aggregate_Salary
FROM Employee e1 JOIN Employee e2
ON e1.id >= e2.id GROUP BY e1.EmpId,
e1.EmpName,
e1.EmpSalary
使用相关子查询:
select EmpId, EmpName, EmpSalary, (select sum(EmpSalary) from Employee e2
where e2.EmpId <= e1.EmpId) as AggregateSalary
from Employee e1
您没有指定您的 DBMS,所以这是 ANSI SQL:
select empid,
empname,
empsalary,
sum(empsalary) over (order by empid) as aggregate_salary
from employee
order by empid;
我有一个 table Employee
.
如何获取 table 的聚合列作为单独的列,如图所示?
我去年遇到的确切问题。希望对您有所帮助。
SELECT e1.EmpId,
e1.EmpName
e1.EmpSalary,
SUM(e2.EmpSalary) AS Aggregate_Salary
FROM Employee e1 JOIN Employee e2
ON e1.id >= e2.id GROUP BY e1.EmpId,
e1.EmpName,
e1.EmpSalary
使用相关子查询:
select EmpId, EmpName, EmpSalary, (select sum(EmpSalary) from Employee e2
where e2.EmpId <= e1.EmpId) as AggregateSalary
from Employee e1
您没有指定您的 DBMS,所以这是 ANSI SQL:
select empid,
empname,
empsalary,
sum(empsalary) over (order by empid) as aggregate_salary
from employee
order by empid;