J
J
Jonny Mirzayev2017-02-22 00:48:50
MySQL
Jonny Mirzayev, 2017-02-22 00:48:50

SQL query to search for users with a filter by age and gender?

The "Users" table has a "birthday" field in the date format (1988-12-31) and a "Gender" field with the values ​​'Male' 'Female'
I want to filter the site search by gender and age, for example (Women up to x age or Men up to age x) where X is determined from today (today)-('birthday')=years and gender is taken from the "Gender" field
Help the newbie how to organize this correctly ?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergei Gribok, 2017-02-22
@FungusWarrior

well something like

SELECT * 
FROM Users
WHERE 
YEAR(date) - YEAR(birthday) - (DATE_FORMAT(date, '%m%d') < DATE_FORMAT(birthday, '%m%d'))<X
AND 
gender = "Male/Female"

D
d-stream, 2017-02-22
@d-stream

SQL was conceived as almost natural language "ask the base":
select [select]
* [all]
from Users [of Users]
where [when/where/which]
gender = Female and (today - birthday) < X [ women and age less x]
or (or)
gender = Male and (today - birthday) < X [men and age less than x]

K
Konstantin Tsvetkov, 2017-02-22
@tsklab

age…(today)-('birthday')=years
It's not years. Age is calculated like this:
CAST( DATEDIFF( Year, BirthDay, ISNULL( DeathDay, GETDATE())) + ( SIGN ( DATEDIFF ( DAY, BirthDay, DATEADD ( YEAR, YEAR( BirthDay ) - YEAR( ISNULL( DeathDay, GETDATE()) ), ISNULL( DeathDay, GETDATE())))) - 1 ) / 2 AS VARCHAR)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question