2010-02-23 154 views
2

我能將SUM()ISNULL()內....考慮我下面的SQL Server的select語句這個sql語法是否正確?

SELECT e.Emp_Id,e.Identity_No,e.Emp_Name,case WHEN e.SalaryBasis=1 
THEN 'Weekly' ELSE 'Monthly' end as SalaryBasis,e.FixedSalary, 
    ISNULL(Adv.Daily_Wage,0) as Advance from Employee as e 
    inner join Designation as d on e.Desig_Id=d.Desig_Id 
    Left Outer Join Payroll as Adv on e.Emp_Id=Adv.Emp_Id where e.Is_Deleted=0 

本聲明做工精細....但是當我申請SUM()內的ISNULL()

SELECT e.Emp_Id,e.Identity_No,e.Emp_Name,case WHEN e.SalaryBasis=1 
    THEN 'Weekly' ELSE 'Monthly' end as SalaryBasis,e.FixedSalary, 
     ISNULL(SUM(Adv.Daily_Wage),0) as Advance from Employee as e 
     inner join Designation as d on e.Desig_Id=d.Desig_Id 
     Left Outer Join Payroll as Adv on e.Emp_Id=Adv.Emp_Id 
     where e.Is_Deleted=0 

我得到了錯誤,

'Employee.Emp_Id'列在無效選擇列表,因爲它不是包含在合計 函數或GROUP BY子句中的 。

任何建議....

回答

2

您需要GROUP BY在選擇其他列。像

SELECT e.Emp_Id, 
     e.Identity_No, 
     e.Emp_Name, 
     case 
      WHEN e.SalaryBasis=1 THEN 'Weekly' 
      ELSE 'Monthly' 
     end as SalaryBasis,e.FixedSalary, 
     ISNULL(SUM(Adv.Daily_Wage),0) as Advance 
from Employee as e inner join 
     Designation as d on e.Desig_Id=d.Desig_Id Left Outer Join 
     Payroll as Adv on e.Emp_Id=Adv.Emp_Id 
where e.Is_Deleted=0 
GROUP BY e.Emp_Id, --This section is what you are missing 
     e.Identity_No, 
     e.Emp_Name, 
     case 
      WHEN e.SalaryBasis=1 THEN 'Weekly' 
      ELSE 'Monthly' 
     end, 
    e.FixedSalary 

東西看一看定義在這裏

GROUP BY (Transact-SQL)

+0

@astander現在它的工作....謝謝,我只是錯過一列... – 2010-02-23 07:52:03

+0

了'case'在' GROUP BY' *對我來說感覺效率低下......您可以用「e.SalaryBasis」來代替。 – bart 2010-02-23 08:46:24