2016-08-25 67 views
0
SELECT Count(*) 
FROM headcount 
WHERE [mso/bu2] = @MSOBU 
     AND [status] = 'billable' 
     AND [location type] = 'offshore' 
     AND [vertical group] = @Vertical 
     AND lob IN(CASE 
        WHEN @LOB = 'dgtl' THEN (SELECT DISTINCT lob 
               FROM lob 
               WHERE category = 'esg') 
        WHEN @LOB = 'nondgtl' THEN (SELECT DISTINCT lob 
               FROM lob 
               WHERE category <> 'esg') 
        WHEN @LOB = '' THEN (SELECT DISTINCT lob 
              FROM headcount) 
        END) 

我陷進這個錯誤,即使我使用IN子句SQL Server子查詢返回了多個值。這當子查詢跟隨不允許=,!=,<, <= , >,> =(即使我使用IN子句)

+0

而不是獨特的嘗試頂部1 –

+0

沒有我不能因爲該列有多個值 – Vickyster

+0

THEN子句可能不會返回超過1個值。 – jarlh

回答

0

你需要像這樣

SELECT Count(*) 
FROM headcount 
WHERE [mso/bu2] = @MSOBU 
     AND [status] = 'billable' 
     AND [location type] = 'offshore' 
     AND [vertical group] = @Vertical 
     AND ((@LOB = 'dgtl' 
       AND lob IN (SELECT DISTINCT lob 
          FROM lob 
          WHERE category = 'esg')) 
       OR (@LOB = 'nondgtl' 
        AND lob IN (SELECT DISTINCT lob 
           FROM lob 
           WHERE category <> 'esg')) 
       OR @LOB = '')) 
+0

@Vickyster - 很高興幫助你。歡迎來到SO,如果我的回答或Mike的回答幫助你解決了這個問題,那麼你可以通過選擇左邊的刻度線來標記它作爲答案,答案對你有幫助 –

+0

是的,我希望但我只有3個聲望。 。我的不好..但我會盡快將此標記爲答案 – Vickyster

0

CASE的操作數WHEN 必須由一個值,而不是多行。

嘗試重寫查詢這樣的:

select COUNT(*) 
    from HeadCount 
    where [MSO/BU2][email protected] and [Status]='billable' 
    and [Location Type]='offshore' and [Vertical Group]= @Vertical 
    and (@LOB='' 
      OR 
     LOB in(
     select distinct lob from LOB 
      where (@LOB='dgtl' and Category ='esg') OR 
       (@LOB='nondgtl' and Category<>'esg') 
       ) 
     ) 

對於@LOB='',因爲它選擇主表(人數)的所有行無子查詢的需要。

相關問題