【问题标题】:Is this sql syntax correct?这个sql语法正确吗?
【发布时间】:2010-02-23 07:41:47
【问题描述】:

我可以在ISNULL() 中应用SUM().... 考虑我下面的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 

此声明工作正常....但是当我在 ISNULL() 中应用 SUM()

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

任何建议....

【问题讨论】:

    标签: sql-server-2005 select sum isnull


    【解决方案1】:

    您需要 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)

    【讨论】:

    • GROUP BY 中的case 感觉对我来说效率低下...你也可以用e.SalaryBasis 分组。
    猜你喜欢
    • 1970-01-01
    • 2011-02-25
    • 2011-05-08
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多