将年龄链接到AgeGroup表

时间:2017-01-05 09:46:23

标签: sql-server sql-server-2016

我有一个客户端表,其中包含Age的计算列。

CREATE TABLE [dbo].[Client]
(
    [ClientID] [int] IDENTITY(1,1) NOT NULL,
    [ClientName] varchar(50) NOT NULL,
    [DOB] [date] NOT NULL,
    [Age]  AS (datediff(year,[DOB],getdate())-case when dateadd(year,datediff(year,[DOB],getdate()),[DOB])>getdate() then (1) else (0) end),
    CONSTRAINT [PK_Client] PRIMARY KEY CLUSTERED 
(
[ClientID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)

然后我有一个具有以下行的AgeGroup表。

AgeGroupID  AgeGroup    StartRange  EndRange
1           65 & over   65          255
2           55-64       55          64
3           45-54       45          54
4           35-44       35          44
5           25-34       25          34
6           19-24       19          24
7           13-18       13          18
8           Below 12    0           12

如何将客户端链接到AgeGroup以在选择查询中显示客户端AgeGroup?

返回输出,如下所示

ClientID  ClientName     Age     AgeGroup
1         Peter Smith    25     25-34

1 个答案:

答案 0 :(得分:1)

也许,这样的事情:

 SELECT c.ClientID
    ,c.ClientName
    ,c.Age
    ,ag.AgeGroup
FROM client c
LEFT JOIN AgeGroup ag
    ON c.age BETWEEN ag.StartRange AND ag.EndRange