1

さて、custid、lastname、firstname、DOBのテーブルがあります。

私の仕事は、顧客が生まれた10年を表す文字列を使用してもう1つの列を作成することです...

つまり、カストが1950年に生まれた場合、そのレコードの新しい列は「50」と表示されます。カストが1974年に発生した場合、そのレコードの新しい列は「70」と表示されます。等々。

私は、10年ごとにグループ化し、カストが生まれた10年の「文字列」表現を与える新しい列を作成する必要があると思います。

これは私の試みです...

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を作成し、「70年代以前、80年代、90年代、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 '='.

私を正しい方向に導いてください。

「setDOBYEAR='SeventiesandBefore'」の代わりに「Print'Seventiesand Before'」を使用できますか?

たぶん、IFステートメントを使用せずにこれを行うことはできますが、方法がわかりません。

ThankX

4

1 に答える 1

4

これを行うためにgroupbyは必要ありません。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 に答える