子查询返回多个值,但我使用“ IN”作为运算符

时间:2018-07-09 19:04:51

标签: sql sql-server

长话短说,我有一个列名为Crosswalk的{​​{1}}表。表中只有一行用于在几个查询中引用各种内容,这种方法对我来说效果很好。但是,当我不得不引用多个值时,将出现以下错误。我真的不知道为什么它不起作用。我看到了很多与此相关的主题/帖子,但是大多数解决方案都声明要使用IN运算符,而我已经是。令人不寒而栗的事情是,无论我使用“ In”还是“ =“”,只要我只调用一个值并删除人行横道表的第二行,它都可以工作。

错误供参考:

  

信息512,第16级,状态1,第2行
  子查询返回的值超过1。当子查询遵循=,!=,<,<=,>,> =或将子查询用作表达式时,不允许这样做。

人行横道表格格式:

MgrFilterRacf

查询:

Id  | AttCeilingScore | AttFloorScore  | MgrFilterRacf    
----+-----------------+----------------+---------------
 1  |    100          |      75        |    Value1    
 2  |    NULL         |     NULL       |    Value2

特定的令人反感的代码行:

--\\*Perform calculation For Attendance Score Sa*\\
Select
    MgrRacf,
    MgrName,
    Ctc.racf as EmpRacf,
    Ctc.EmpName,
    Case 
       when AttCntSegment is null then 0
       else AttCntSegment 
    end as AttCntSegment,
    Case 
       when AttSumDuration is null then 0
       else AttSumDuration 
    end as AttSumDuration,
    case
       when AttCntSegment > 12 
          then (Select AttFloorScore from tblAvs1Scoring)
       when AttCntSegment is null 
          then (Select AttCeilingScore from tblAvs1Scoring)
       when 100 - ((AttCntSegment) * 2 + PercentReduction) < (Select AttFloorScore from tblAvs1Scoring) 
          then (Select AttFloorScore from tblAvs1Scoring)
       else 100 - ((AttCntSegment)*2+PercentReduction)
    end As AttScore,
    Case
       when AttCntSegment is null then 100
       else 100 - ((AttCntSegment)*2+PercentReduction) 
    end as AttScoreRaw,
    'RollSixSum' as ReportTag
From
    (--\\*Get Total Occurrences from Rolling 6 months per advocate*\\
     SELECT 
         EMP_ID,
         COUNT(SEG_CODE) AS AttCntSegment, 
         SUM(DURATION) AS AttSumDuration
     FROM   
         tblAttendance AS Att
     WHERE  
         (START_DATE >= Getdate() - 180) 
         AND (SEG_CODE NOT IN ('FLEX2', 'FMLA'))
         AND (DURATION > 7)
         AND START_DATE IS NOT NULL
     GROUP BY 
         EMP_ID) As Totals
INNER JOIN 
    tblCrosswalkAttendanceTime AS Time ON AttSumDuration BETWEEN Time.BegTotalTime AND Time.EndTotalTime
RIGHT JOIN 
    tblContactListFull AS Ctc ON Ctc.employeeID = Totals.EMP_ID
WHERE
    --Ctc.Mgr2racf IN ('Value1','Value2')   --This works
    Ctc.Mgr2racf IN (SELECT MgrFilterRacf FROM tblAvs1Scoring) --This returns the same 2 values but doesn't work, note works with only 1 value present
    AND (title LIKE '%IV%' OR Title LIKE '%III%' OR title LIKE '%Cust Relat%')  --Going to apply same logic here once I have a solution
    AND employeestatus2  <> 'Inactive'

2 个答案:

答案 0 :(得分:4)

不是IN子句引起了错误,因为IN不必只返回1个值。相反,它可能在这里:

CASE ... < (Select AttFloorScore from tblAvs1Scoring)

尝试select count(AttFloorScore) from tblAvs1Scoring,看看它是否>1。我确定是。

可以通过任何适合您数据的方法来缓解这种情况。

  1. 使用TOP 1
  2. 使用类似MAX()的聚合
  3. 关联子查询以限制返回的行。
  4. 使用适当的WHERE子句

答案 1 :(得分:0)

万一有人在读这个,我真是个白痴。错误不是我想的那样,它在那些子查询中位于查询的顶部。即使不存在任何值,由于我添加了一行以返回最大值,因此仍需要告知它。一旦我更新,一切都很好并且可以正常工作。

底线,请检查所有子查询。不要像我这样的工具。