2013-10-11 60 views
1

表数据和结构:case语句在SQL Server中创建X场和where子句X字段2008

Name  DateOfBirth 
Thuso  1987-02-27 00:00:00.000 
Sue  1968-02-27 00:00:00.000 
Zee  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 ([email protected]) 

它产生的输出我没有想到的问题:

X 
1 
2 
3 

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

X 
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 

OR

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 ([email protected]) 
+0

Ahaaa!超过托马斯一百万倍,这就是我一直在寻找的东西。 –