sql 按年龄范围分组更新列
sql group update column by age range
我想将33岁的class列更新为2,34-35岁class列为3,36岁class 列为 4。我正在使用 Microsoft SQL 服务器。
ID DATE_OF_BIRTH CLASS
1 10.10.1986 1
2 11.02.1987 2
2 18.04.1988 3
.....................
.....................
.....................
您可以在计算人员年龄时使用 case
表达式更新 table:
UPDATE mytable
SET class = CASE DATEDIFF(YEAR, date_of_birth, GETDATE())
WHEN 33 THEN 2
WHEN 34 THEN 3
WHEN 35 THEN 3
WHEN 36 THEN 4
ELSE class -- safeguard
END
UPDATE YourTableName
SET CLASS = CASE WHEN DATEDIFF(year, DATE_OF_BIRTH, GETDATE()) = 33 THEN 2
WHEN DATEDIFF(year, DATE_OF_BIRTH , GETDATE()) BETWEEN 34 AND 35 THEN 3
WHEN DATEDIFF(year, DATE_OF_BIRTH , GETDATE()) = 36 THEN 4
ELSE CLASS
END
我想将33岁的class列更新为2,34-35岁class列为3,36岁class 列为 4。我正在使用 Microsoft SQL 服务器。
ID DATE_OF_BIRTH CLASS
1 10.10.1986 1
2 11.02.1987 2
2 18.04.1988 3
.....................
.....................
.....................
您可以在计算人员年龄时使用 case
表达式更新 table:
UPDATE mytable
SET class = CASE DATEDIFF(YEAR, date_of_birth, GETDATE())
WHEN 33 THEN 2
WHEN 34 THEN 3
WHEN 35 THEN 3
WHEN 36 THEN 4
ELSE class -- safeguard
END
UPDATE YourTableName
SET CLASS = CASE WHEN DATEDIFF(year, DATE_OF_BIRTH, GETDATE()) = 33 THEN 2
WHEN DATEDIFF(year, DATE_OF_BIRTH , GETDATE()) BETWEEN 34 AND 35 THEN 3
WHEN DATEDIFF(year, DATE_OF_BIRTH , GETDATE()) = 36 THEN 4
ELSE CLASS
END