3

Is it possible to extract an integer value from day names, i.e. "Mon", Tue", "Wed" with an SQL statement?

For example:

 Mon = 1
 Tue = 2
 Wed = 3
Templar
  • 1,843
  • 7
  • 29
  • 42
mouthpiec
  • 3,923
  • 18
  • 54
  • 73

4 Answers4

9

Try FIELD:

SELECT FIELD('Mon', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
    -> 1
SELECT FIELD('Thu', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
    -> 4

http://dev.mysql.com/doc/refman/5.4/en/string-functions.html#function_field

awgy
  • 16,596
  • 4
  • 25
  • 18
5

If you simply have a non-datetime field with just Mon, Tue, Wed, etc, you can use the STR_TO_DATE() and WEEKDAY() functions to come up with something like this:

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', yourField), '%X%V %W')) + 1 AS WeekIndex;

Test Case:

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', 'Mon'), '%X%V %W')) + 1 AS WeekIndex;
+-----------+
| WeekIndex |
+-----------+
|         1 |
+-----------+

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', 'Tue'), '%X%V %W')) + 1 AS WeekIndex;
+-----------+
| WeekIndex |
+-----------+
|         2 |
+-----------+

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', 'Wed'), '%X%V %W')) + 1 AS WeekIndex;
+-----------+
| WeekIndex |
+-----------+
|         3 |
+-----------+

SELECT WEEKDAY(STR_TO_DATE(CONCAT('201011 ', 'Thu'), '%X%V %W')) + 1 AS WeekIndex;
+-----------+
| WeekIndex |
+-----------+
|         4 |
+-----------+
Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
1

If your field is a date field, just use

SELECT DATE_FORMAT(my.field, "%w");

More Info on MySQLs DATE_FORMAT can be optained here.

Bjoern
  • 15,934
  • 4
  • 43
  • 48
1
DAYOFWEEK(date);

http://www.tutorialspoint.com/mysql/mysql-date-time-functions.htm#function_dayofweek

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
bvp
  • 11
  • 1