SQL Server Retrieve the names and birthdates of all people from the "people" table [closed]

sg24os4d  于 2023-11-16  发布在  其他
关注(0)|答案(2)|浏览(92)

Closed. This question needs details or clarity . It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post .

Closed 8 years ago.
Improve this question

I would like to get the names from a user table if the users' birthday is today.

User table

name  |   date of birth
------+-----------------
name1 |   20/05/1991
name2 |   05/01/1995
name3 |   05/01/1991

If I supply: 05/01/2015 as parameter, it should display name2 and name3 .

Can anyone tell me the SQL query required for filtering the results by the date parameter.

vmpqdwk3

vmpqdwk31#

This query should work for you:

SELECT NAME, [DATE OF BIRTH]
FROM TABLE
WHERE DAY([DATE OF BIRTH]) = DAY(GETDATE())
    AND MONTH([DATE OF BIRTH]) = MONTH(GETDATE())

Here is a SQLFiddle with the query based on your sample data.

My initial answer was incorrect because it was actually looking for the same date between GETDATE() with the DATE OF BIRTH which is incorrect if you are looking for people who have birthdays today (because birthdays are not dependant on year, but on month and day).

flvtvl50

flvtvl502#

SELECT [DATE OF BIRTH], Name
FROM [TABLE]
WHERE datepart(dd,[DATE OF BIRTH]) = datepart(dd,GETDATE()) 
AND datepart(mm,[DATE OF BIRTH]) = datepart(mm,GETDATE())

For getting list for a range of dates:

declare @StartDate DATE
declare @EndDate DATE

SELECT [DATE OF BIRTH], Name
FROM [TABLE]
WHERE 
datepart(dd,[DATE OF BIRTH]) between datepart(dd,@StartDate) 
AND datepart(dd,@EndDate)   

AND datepart(mm,[DATE OF BIRTH]) between datepart(mm,@StartDate) 
AND datepart(mm,@EndDate)

相关问题