2016-04-28 221 views
0
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 

我要工資的一定比例列(工資/ TotalSalary)* 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'. 
+0

'爲了通過Id'錯過了'在()''的[薪水] /總和(工資)在()'裏面 – Arulkumar

+0

改變你在()來匹配running_total - OVER(ORDER由Id) –

回答

1

給出了在將乘法錯誤,因爲該部門將總是導致小於1你wouldnot乘看到他們,除非你通過100.0。你也應該使用​​3210來處理null的值。

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
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]