1

表数据和结构:

姓名 出生日期
因此 1987-02-27 00:00:00.000
苏 1968-02-27 00:00:00.000
泽 1999-02-27 00:00:00.000

询问:

USE [PersonDatabase]
GO

DECLARE @AGE int  =1
Select Name, X=CASE
   WHEN( ( year(getdate()) - year(DateOfBirth)) >=0 AND (year(getdate()) - year(DateOfBirth)) <=17) THEN 1
   WHEN( ( year(getdate()) - year(DateOfBirth)) >= 18 AND (year(getdate()) - year(DateOfBirth)) <=29) THEN 2
   WHEN( ( year(getdate()) - year(DateOfBirth)) >= 30 AND (year(getdate()) - year(DateOfBirth)) <=60) THEN 3
END
froM PersonDatabase.mem.Namebirth
WHERE (X=@AGE)

它产生的输出不是预期的:

X
1
2
3

我的问题是:我在查询的 CLAUSE 中哪里出错了WHERE,它产生的输出为:

X
1
4

1 回答 1

3

我看到了两种修复查询的方法:

DECLARE @AGE int  =1
Select Name, CASE
   WHEN( ( year(getdate()) - year(DateOfBirth)) >=0 AND (year(getdate()) - year(DateOfBirth)) <=17) THEN 1
   WHEN( ( year(getdate()) - year(DateOfBirth)) >= 18 AND (year(getdate()) - year(DateOfBirth)) <=29) THEN 2
   WHEN( ( year(getdate()) - year(DateOfBirth)) >= 30 AND (year(getdate()) - year(DateOfBirth)) <=60) THEN 3
END
froM PersonDatabase.mem.Namebirth
WHERE 
CASE
       WHEN( ( year(getdate()) - year(DateOfBirth)) >=0 AND (year(getdate()) - year(DateOfBirth)) <=17) THEN 1
       WHEN( ( year(getdate()) - year(DateOfBirth)) >= 18 AND (year(getdate()) - year(DateOfBirth)) <=29) THEN 2
       WHEN( ( year(getdate()) - year(DateOfBirth)) >= 30 AND (year(getdate()) - year(DateOfBirth)) <=60) THEN 3
    END = @AGE

或者

SELECT Name, X FROM(
  Select Name, X=CASE
     WHEN( ( year(getdate()) - year(DateOfBirth)) >=0 AND (year(getdate()) - year(DateOfBirth)) <=17) THEN 1
     WHEN( ( year(getdate()) - year(DateOfBirth)) >= 18 AND (year(getdate()) - year(DateOfBirth)) <=29) THEN 2
     WHEN( ( year(getdate()) - year(DateOfBirth)) >= 30 AND (year(getdate()) - year(DateOfBirth)) <=60) THEN 3
  END
  froM PersonDatabase.mem.Namebirth
) T
WHERE (T.X=@AGE)
于 2013-10-11T15:03:16.907 回答