loading..
Русский    English
16:12

Sorting in order of days of birth

Such a sorting may be useful for getting the order of celebration of employees' DOB.
The feature of this sorting is in ordering dates firstly by month, then by day of month without taking into account the year of birth at all. 

Let's consider the Battles table as an example, namely date column. It is evident that ordering by date does not required result due to the year (for example, October 20 follows after November 15):

Console
Execute
  1. SELECT date
  2. FROM Battles
  3. ORDER BY date;

date
1941-05-25 00:00:00.000
1942-11-15 00:00:00.000
1943-12-26 00:00:00.000
1944-10-25 00:00:00.000
1962-10-20 00:00:00.000
1962-10-25 00:00:00.000

To solve the problem, two methods can be suggested (in  SQL(Structured Query Language) is a database computer language designed for the retrieval and management of data in relational database management systems (RDBMS), database schema creation and modification, and database object access control management.SQL Server dialect).

1. Use of  CONVERT function

In so doing, we transform datetime value to the string representation in the format "mm-dd"

Console
Execute
  1. SELECT CONVERT(CHAR(5), date, 110) "mm-dd"
  2. FROM Battles;
and the latter is used in sorting

Console
Execute
  1. SELECT date
  2. FROM Battles
  3. ORDER BY CONVERT(CHAR(5),date,110);

date
1941-05-25 00:00:00.000
1962-10-20 00:00:00.000
1962-10-25 00:00:00.000
1944-10-25 00:00:00.000
1942-11-15 00:00:00.000
1943-12-26 00:00:00.000

2. Use of  MONTH and DAY functions

Here we use built-in functions which return date components - month (MONTH) and day (DAY) respectively. Let's do sorting on these components:

Console
Execute
  1. SELECT date
  2. FROM Battles
  3. ORDER BY MONTH(date), DAY(date);

As regards query performance, you can choose any method because optimizer produces identical execution plans for these.

Finally let's give the last query in a more presentable form having included in it additionally a "hero of the festivities":

Console
Execute
  1. SELECT DAY(date) BD_day, DATENAME(mm, date) BD_month, name
  2. FROM Battles
  3. ORDER BY MONTH(date), DAY(date);

Bookmark and Share
Tags
aggregate functions Airport ALL AND AS keyword ASCII AVG Battles Bezhaev Bismarck C.J.Date calculated columns Cartesian product CASE cast CHAR CHARINDEX Chebykin check constraint classes COALESCE common table expressions comparison predicates Computer firm CONSTRAINT CONVERT correlated subqueries COUNT CROSS APPLY CTE data type conversion data types database schema DATEADD DATEDIFF DATENAME DATEPART DATETIME date_time functions DDL DEFAULT DEFAULT VALUES DELETE DISTINCT DML duplicates edge equi-join EXCEPT exercise (-2) More tags
The book was updated
month ago
https://exchangesumo.com/obmen/WEXRUB-QIWIRUB/
©SQL-EX,2008 [Evolution] [Feedback] [About] [Links] [Team]
All right reserved.