SQL Server变得最老,最年轻

时间:2014-08-24 13:32:53

标签: sql-server-2008 tsql

我有一张带有他们出生日期的人的表,想知道最年轻和最年长的人。

我正在尝试编写此代码,但它无效。我该怎么做?

SELECT [CustNo]
      ,[name]
      ,[address]
      ,max([Date of Birth]) and min([Date of Birth]), 
      ,[id]
  FROM [Bharath].[dbo].[Customer]

这是表格

enter image description here

我想要做的另一个代码。

 SELECT  CustNo, name, address, DATEDIFF(YEAR, [Date of Birth], GETDATE()) AS Age
FROM bharath.dbo.Customer
INNER JOIN (SELECT min [Date of Birth] y , Max [Date of Birth] z FROM Customer) a
 on a.y=dob 
 or a.z=dob

这是完全满足我所有需求的代码

select [CustNo], [name], [address],datediff(year, [date of birth], getdate()) as age , CONVERT(VARCHAR(10),[Date of Birth],105)
from Bharath.dbo.Customer
where [Date of Birth] = (select max([Date of Birth]) from Bharath.dbo.Customer) 
or [Date of Birth] = (select min([Date of Birth]) from Bharath.dbo.Customer)

2 个答案:

答案 0 :(得分:2)

这将为您提供[出生日期]最低和最高的人员列表:

select [CustNo], [name], [address], [Date of Birth], [id] 
from customer
where [Date of Birth] = (select max([Date of Birth]) from customer) 
or [Date of Birth] = (select min([Date of Birth]) from customer)

它不会告诉你哪个是最年轻或最老的,但这应该从[出生日期]明显。如果多人共享相同的[出生日期],它将全部归还。

如果您想要最年轻和最早的查询:

-- youngest
select [CustNo], [name], [address], [Date of Birth], [id] 
from customer
where [Date of Birth] = (select max([Date of Birth]) from customer) 

-- oldest
select [CustNo], [name], [address], [Date of Birth], [id] 
from customer
where [Date of Birth] = (select min([Date of Birth]) from customer)

要计算年龄,由于缺乏处理闰年而不精确,您可以将其添加到select语句中:

case 
    when month(getdate()) < month([date of birth]) then datediff(year, [date of birth], getdate()) - 1
    when month(getdate()) = month([date of birth]) and day(getdate()) < day([date of birth]) then datediff(year, [date of birth], getdate()) 
    when month(getdate()) >= month([date of birth]) and day(getdate()) >= day([date of birth]) then datediff(year, [date of birth], getdate()) 
end as Age

我确定Google搜索应该找到更好/更精确的计算年龄的方法。

答案 1 :(得分:1)

您可以使用RANK获取行的最小和最大出生日期

WIth CTE as (

  SELECT [CustNo]
      ,[name]
      ,[address]
      ,RANK() OVER ( ORDER BY [Date of Birth] asc) MINDATERANK 
      ,RANK() OVER ( ORDER BY [Date of Birth] desc) MAXDATERANK
      ,[Date of Birth] 
      ,[id]
  FROM [Bharath].[dbo].[Customer]
)
SELECT * FROM CTE
Where MINDATERANK = 1 or MAXDATERANK= 1

如果您有最小或最大生日的关系,则假设您需要多行 如果你只需要每行最小和最大一行,你可以使用ROW_NUMBER而不是rank。