1

好的,所以我有一个表,其中有 custid、lastname、firstname 和 DOB。

我的任务是再创建一个包含客户出生十年的字符串的列...

即,如果 cust 出生于 1950 年,则该记录的新列应显示为 50 年代,如果 cust 出生于 1974 年,则该记录的新列应显示为 70 年代。等等。

我想我必须按每个十年分组,并创建一个新列,给出客户出生十年的“字符串”表示。

这是我的尝试...

Select DateOfBirth, COUNT(DateOfBirth) as 'DOBYEAR' From Customers Group by DateOfBirth Order By DateOfBirth asc If (Customers.DateOfBirth <= '1979') begin set DOBYEAR = 'Seventies and Before' end If (Customers.DateOfBirth between '1980' and '1989)' begin set DOBYEAR = 'Eighties' end If (Customers.DateOfBirth between '1990' and '1999') begin set DOBYEAR = 'Nineties' end If Customers.DateOfBirth >= '2000' Begin set DOBYEAR = '20th century' end Go

我正在创建 DOBYEAR 作为新列,并尝试输入诸如“七十年代和之前、八十年代、九十年代和 20 世纪......

给我以下错误。

Msg 102, Level 15, State 1, Line 6
Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 10
Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near '='.
Msg 102, Level 15, State 1, Line 18
Incorrect syntax near '='.

请指导我正确的方向。

我可以使用“Print 'Seventies and Before'”而不是“set DOBYEAR = 'Seventies and Before'”吗?

也许,我可以在不使用 IF 语句的情况下做到这一点,但不知道如何。

谢谢X

4

1 回答 1

4

您不需要 group by 来执行此操作。假设DateOfBirth列是类型datetime(提示:应该):

Select 
    DateOfBirth, 
    Case 
      when datepart(year, DateOfBirth) between 1970 and 1979 then 'Seventies' 
      when datepart(year, DateOfBirth) between 1980 and 1989 then 'Eighties' 
      when datepart(year, DateOfBirth) between 1990 and 1999 then 'Nineties' 
      when datepart(year, DateOfBirth) >= 2000 then '21st century' 
      else 'Before 1970' 
    end as DOBDecadeString
From 
   Customers
Order By DateOfBirth asc
于 2012-05-08T00:01:17.850 回答