2

what I am trying to do is: sort people in database after date of birth (nvarchar, not date type) the date is in this string format: dd-MM-yyyy and by Sort, i mean return a list of all the people, but sorted after the date of birth, to Fill a datagridview.

I have a column with the date of birth, which is nvarchar. I want to store the day, the month and the year in 3 variables in the sql query, and also test them in order to put them in order.

what I tried is:

SELECT SUBSTRING(date_of_birth,0,2) FROM people AS zi;
SUBSTRING(date_of_birth,3,2) AS luna
SUBSTRING(date_of_birth,6,4) AS an
SELECT [id], [specie], [sex], [date_of_birth], [greutate] FROM [people] WHERE

but I really don't know how to figure it out from now on...

1

2 Answers 2

4
SELECT
  [id], [specie], [sex], [date_of_birth], [greutate],
  SUBSTRING(date_of_birth,6,4)  AS [an],
  SUBSTRING(date_of_birth,3,2)  AS [luna],
  SUBSTRING(date_of_birth,0,2)  AS [zi]
FROM
  [people]
ORDER BY
  SUBSTRING(date_of_birth,6,4),
  SUBSTRING(date_of_birth,3,2),
  SUBSTRING(date_of_birth,0,2)

Many RDBMS also allow this...

SELECT
  [id], [specie], [sex], [date_of_birth], [greutate],
  SUBSTRING(date_of_birth,6,4)  AS [an],
  SUBSTRING(date_of_birth,3,2)  AS [luna],
  SUBSTRING(date_of_birth,0,2)  AS [zi]
FROM
  [people]
ORDER BY
  [an], [luna], [zi]
Sign up to request clarification or add additional context in comments.

13 Comments

"Many RDBMS also allow this..." (Yep, even MySQL)
would something change if I want to order the people by their age? what should I calculate or... ?
@HoreaMihuţ - Ordering by DoB is mathematically the same as ordering by age... Someone who is older has a DoB longer ago...
I've tried it, and only checked if the year is sorted ok, but it's not. I've put exactly your code in the query.
@HoreaMihuţ - Have you checked that your substrings are correct? (I copied them from your code, but I suspect that they're slightly out.)
|
0

Try this..

.

SELECT
[id], [specie], [sex], [date_of_birth], [greutate]
From
[People]
ORDER BY
Convert(DateTime, date_of_birth, 105) Asc

.

.

By converting the column into DateTime type 105, you can get it to a format of 'dd-MM-yyyy'

Paste this code as it is and try..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.