计算每个员工

时间:2016-04-28 13:44:33

标签: sql sql-server window-functions

ID  Name     Age    Salary  running_total   Percentage
1   Abe      61     140000  140000             0
2   Bob      34     44000   184000             0
5   Chris    34     40000   224000             0
7   Dan      41     52000   276000             0
8   Ken      57     115000  391000             0
11  Joe      38     NULL    391000             NULL

我想要薪水的百分比列为(薪水/总薪资)* 100。

我试过这个,但总是给出0。

  Select [ID]
      ,[Name]
      ,[Age]
      ,[Salary], Sum(Salary) Over(order by Id) As running_total, [Salary]/Sum(Salary)  Over() as Percentage
  From [Company].[dbo].[SalesPerson]

我甚至无法应用乘法运算。查询给出了乘法乘以100的错误。

Incorrect syntax near the keyword 'Over'.

2 个答案:

答案 0 :(得分:1)

因为除非你乘以100.0,否则除法总是小于1,你就不会看到它们。您还应该使用null处理coalesce值。

Select [ID]
      ,[Name]
      ,[Age]
      ,[Salary], Sum(coalesce(Salary,0)) Over(order by Id) As running_total, 
      100.0*coalesce([Salary],0)/Sum(coalesce(Salary,0))  Over() as Percentage
  From [Company].[dbo].[SalesPerson]

答案 1 :(得分:1)

 Select [ID]
      ,[Name]
      ,[Age]
      ,[Salary]
      ,Sum(Salary) Over(order by Id) As running_total
      ,CAST([Salary] as decimal(18,2)) * 100 / Sum(Salary) Over() as Percentage
  From [Company].[dbo].[SalesPerson]