由于逐个语句而导致错误的SQL查询(INVALID COLUMNS)

时间:2016-03-10 04:43:55

标签: sql sql-server

我有以下SQL:

  DECLARE @EmpId AS Varchar(20),
          @CompanyId as VARCHAR(20),
          @DepartmentId AS VARCHAR(20),
          @DesignationId AS VARCHAR(20),
          @GradeId AS VARCHAR(20),
          @FromDate AS DATE,
          @TillDate AS DATE 

SET @EmpId = null
SET @CompanyId = NULL
SET @DepartmentId = NULL
SET @DesignationId = NULL
SET @GradeId = NULL
SET @FromDate = '1-1-2015'
SET @TillDate = '1-1-2016'

SELECT
    LA.EmpId,AT.IsPaid AS 'IsPaid',
    AT.AttendanceTypeCode, 
    (SELECT DISTINCT IsPaid  
     FROM LeaveApproval 
     WHERE empid = LA.EmpId) AS 'testPAID',
    SUM(CASE WHEN AT.IsPaid = 1 THEN 1 END) AS Paid,
    COUNT(CASE WHEN AT.IsPaid = 0 THEN AT.AttendanceTypeCode END) AS UnPaid,
    COUNT(AT.AttendanceTypeCode) AS LeaveCount
FROM
    LeaveApproval LA
INNER JOIN 
    AttendanceTypes AT ON LA.AttendanceTypeId = AT.AttendanceTypeId
INNER JOIN 
    EmpMaster EM ON LA.Empid = EM.EmpId 
WHERE
    EM.ActiveInActive <> 1 AND 
    EM.EmpId  = CASE WHEN ISNULL(@EmpId ,'-1') <> '-1' AND @EmpId <> ''  
                        THEN @EmpId 
                        ELSE EM.EmpId 
                END
    AND EM.CompanyId = CASE WHEN ISNULL(@CompanyId ,'-1') <> '-1' AND @CompanyId <>     '' 
                              THEN @CompanyId 
                              ELSE EM.CompanyId 
                       END
    AND EM.DepartmentId = CASE WHEN ISNULL(@DepartmentId,'-1') <> '-1' AND @DepartmentId<> ''  
                                 THEN @DepartmentId 
                                 ELSE EM.DepartmentId 
                          END
    AND ISNULL(EM.DesignationId, '')  = CASE WHEN ISNULL(@DesignationId ,'-1') <>  '-1' AND @DesignationId <> '' THEN @DesignationId ELSE ISNULL(EM   .DesignationId,'') END
    AND ISNULL(EM.GradeId,'')  = CASE WHEN ISNULL(@GradeId ,'-1') <> '-1' AND @GradeId <> '' THEN @GradeId ELSE ISNULL(EM .GradeId,'') END
    AND FromDate BETWEEN @FromDate AND  @TillDate 
GROUP BY
    LA.EmpID, AT.AttendanceTypeCode, AT.IsPaid, Paid, UnPaid

以上SQL无效。

我收到错误

  

PaidInPaid无效。

我所知道的是&#39;支付&#39;和Unpaid来自子查询,并且在选择列表的组中不可用。

我的问题是如何在运行我的SQL后达到上述结果我的结果应该重复相同的值,即每个Paid的{​​{1}}的总和

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

您无法在其SELECT中使用当前GROUP BY列的别名。你必须这样做:

Group By LA.EmpID,AT.AttendanceTypeCode,AT.IsPaid,SUM(CASE WHEN AT.IsPaid=1 Then 1 END), COUNT(CASE WHEN AT.IsPaid=0 Then AT.AttendanceTypeCode END)

或者按照您在外部查询中的计划,将所有SELECT用作子查询和

答案 1 :(得分:0)

true

使用CTE在查询中添加新列。像这样修改您的查询。希望它对你有用