2013-09-25 55 views
0
SELECT *, 
    CASE 
    when PERSONNUM in ('x','y','z') 
    then 'Home' 
    end as HomeEmployees 
    when PERSONNUM in ('a','b','c') 
    then 'Away' 
    end as AwayEmployees 
FROM dbo.ALLTOTALS 
where PERSONNUM in ('a','b','c','x','y','z') 
    and HomeEmployees is not null 

--multiple whens基於選擇PERSONNUM領域SQL Server 2008中 - 從殼體迴流不爲空值時,聲明

+0

邏輯問題。想要僅從我創建的列中返回非空值。謝謝 – user2800758

回答

2

爲什麼不從

where HomeEmployees is not null 

修改WHERE條款列入

WHERE PERSONNUM IN ('x', 'y', 'z') 

所以只有在列中的值爲x , y, z的記錄僅被選中。

+2

@ user2800758 - 在'HomeEmployees'選擇'Home'之後應該做的。不需要'CASE'。 – HABO

0

您也可以投射的情況下進入一個別名,然後用一個外部查詢過濾它,像這樣:

SELECT * -- Or better still, explicitly identify each needed column 
FROM 
(
    SELECT *, -- Or better still, explicitly identify each needed column 
    CASE 
     WHEN PERSONNUM in ('x','y','z') 
     THEN 'Home' 
     END AS HomeEmployees 
    FROM AllTotals 
) AS FilteredEmployees 
WHERE 
    FilteredEmployees.HomeEmployees IS NOT NULL; 

或者作爲一個CTE:

WITH FilteredEmployees AS 
(
    SELECT *, 
    CASE 
     WHEN PERSONNUM in ('x','y','z') 
     THEN 'Home' 
     END AS HomeEmployees 
    FROM AllTotals 
) 
SELECT * 
    FROM FilteredEmployees 
    WHERE FilteredEmployees.HomeEmployees IS NOT NULL; 
0

Logical order of execution(見「邏輯處理SELECT語句的順序「)以下SELECT聲明:

DECLARE @MyTable TABLE 
(
    ID  INT IDENTITY PRIMARY KEY, 
    [Date] SMALLDATETIME NOT NULL, 
    WorkingTime INT NOT NULL, 
    EmployeeID INT NULL 
); 
INSERT @MyTable ([Date], WorkingTime, EmployeeID) 
SELECT '20130801', 1, 123 UNION ALL 
SELECT '20130802', 0, 124 UNION ALL 
SELECT '20130803', 0, 125; 

SELECT x.ID, 
     CASE WHEN x.ID % 2 = 1 THEN x.ID END AS EmployeeID 
FROM @MyTable x 
WHERE EmployeeID IS NOT NULL; 

  1. FROM @myTable X
  2. WHERE僱員IS NOT NULL(< => WHERE x.EmployeeID IS NOT NULL)
  3. SELECT x.ID,CASE ... END AS僱員

如您所見,CASE ... END AS EmployeeID表達式評估爲AFTERWHERE子句。這也意味着EmployeeID IS NOT NULL謂詞引用x.EmployeeID列而不是EmployeeID別名從SELECT子句。

這是我得到的結果如下理由:如果你想通過EmployeeID別名來篩選,那麼你可以使用這些解決方案之一

ID   EmployeeID 
----------- ----------- 
1   1 
2   NULL 
3   3 

SELECT x.ID, 
     CASE WHEN x.ID % 2 = 1 THEN x.ID END AS EmployeeID 
FROM @MyTable x 
WHERE CASE WHEN x.ID % 2 = 1 THEN x.ID END IS NOT NULL; 

SELECT * 
FROM 
(
SELECT x.ID, 
     CASE WHEN x.ID % 2 = 1 THEN x.ID END AS EmployeeID 
FROM @MyTable x 
) src 
WHERE src.EmployeeID IS NOT NULL; 

注:這是使用與列名同名的別名不是一個好主意。這造成混亂。

相關問題