在SQL SERVER中分组/打印相关的查询

时间:2012-05-07 23:54:35

标签: sql sql-server database error-handling

好的,我有一张桌子,里面有custid,lastname,firstname和DOB。

我的任务是创建一个包含字符串的列,该字符串给出了客户诞生的十年......

即。如果遗产出生于1950年,该记录的新专栏应该说,五十年代, 如果遗产出生于1974年,该记录的新专栏应该说是七十年代。等等。

我想我必须按照每十年的时间进行分组并制作一个新的专栏,其中给出了该术语诞生十年的“字符串”表示。

这是我的尝试...

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作为新列,并尝试输入字符串,如“七十年代以及八十年代,九十年代和二十世纪......

给我以下错误。

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 '='.

请指导我正确的方向。

我可以使用“打印七十年代及之前”代替“设置DOBYEAR ='七十年代及之前'”吗?

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

ThankX

1 个答案:

答案 0 :(得分:4)

您不需要分组来执行此操作。假设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