这个sql语法是否正确?

时间:2010-02-23 07:41:48

标签: sql-server-2005 select sum isnull

我可以在SUM()中应用ISNULL() ....考虑我的以下sql server select语句

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子句。

任何建议....

1 个答案:

答案 0 :(得分:2)

您需要GROUP BY SELECT中的其他列。像

这样的东西
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)