使用HR数据库进行练习之日期和时间函数
Practice 1
编写一条SQL查询语句,显示当前月份前三个月的月份的第一天(datetime格式)
例如当前:2017-12-08
期望结果:2017-09-01
1 |
SELECT CAST(CONCAT(YEAR(CURRENT_DATE()), '-', MONTH(CURRENT_DATE())-3, '-', '01') AS DATE); |
Practice 2
编写一条SQL查询语句,显示当前月份前三个月的月份的最后一天(datetime格式)
1 |
SELECT LAST_DAY(DATE_SUB(CURRENT_DATE(), INTERVAL 3 MONTH)); |
Practice 3
编写一条SQL查询语句,显示今年的第一天
1 |
SELECT MAKEDATE(EXTRACT(YEAR FROM CURRENT_DATE()), 1); |
Practice 4
编写一条SQL查询语句,显示今年的最后一天
1 |
SELECT (STR_TO_DATE(CONCAT(12, 31, YEAR(CURRENT_DATE())), '%m%d%Y')); |
Practice 5
编写一条SQL查询语句,显示你的年龄
1 2 3 4 |
SELECT YEAR(CURRENT_TIMESTAMP) - YEAR("1992-04-09") - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT("1992-04-09", 5)) as age; |
Practice 6
编写一条SQL查询语句,按照如下格式显示日期
示例日期:2014-09-04
输出日期:September 4,2014
1 |
SELECT DATE_FORMAT(CURRENT_DATE(), '%M %e, %Y'); |
Practice 7
编写一条SQL查询语句,获取使用Thursday September 2014的格式显示当前时间
1 |
SELECT DATE_FORMAT(CURRENT_DATE(), '%W %M %Y'); |
Practice 8
编写一条SQL查询语句,获取当前时间的准确年份
1 |
SELECT YEAR(CURRENT_DATE()); |
Practice 9
编写一条SQL查询语句,获取从一个给定的值获取DATE值
示例值:730677
输出日期:2000-07-11
1 |
SELECT FROM_DAYS(730677); |
Practice 10
编写一条SQL查询语句,获取雇用日期在‘1987-06-01’到‘1987-07-30’间的employee的first name和hire datge
1 2 |
SELECT first_name, hire_date FROM employees WHERE hire_date BETWEEN '1987-06-01' AND '1987-07-30'; |
Practice 11
编写一条SQL查询语句,按照下面的示例格式显示当前日期
输出示例:Thursday 4th September 2014 00:00:00
1 |
SELECT DATE_FORMAT(CURRENT_TIMESTAMP(), '%W %D %M %Y %T') ; |
Practice 12
编写一条SQL查询语句,按照下面的格式显示当前时间
输出示例:05/09/2014
1 |
SELECT DATE_FORMAT(CURRENT_DATE(), '%d/%m/%Y'); |
Practice 13
编写一条SQL查询语句,按照如下格式显示当前时间
1 |
SELECT DATE_FORMAT(CURRENT_TIMESTAMP(), '%h:%i %p %b %e, %Y'); |
Practice 14
编写一条SQL查询语句,显示六月入职的employee的first name,last name
1 2 |
SELECT first_name, last_name FROM employees WHERE MONTH(hire_date) = 6; |
Practice 15
编写一条SQL查询语句,显示超过10个employees加入的年份
1 2 |
SELECT YEAR(hire_date) FROM employees GROUP BY YEAR(hire_date) HAVING COUNT(*) > 10; |
Practice 16
编写一条SQL查询语句,显示在1987年加入的employee的first name
1 |
SELECT first_name FROM employees WHERE YEAR(hire_date) = 1987; |
Practice 17
编写一条SQL查询语句,显示工作经验超过5年的manager的department名字,manager的名字和薪酬
1 2 3 |
SELECT department_name, first_name, salary FROM departments d JOIN employees e ON d.manager_id = e.manager_id WHERE DATEDIFF(CURRENT_DATE(), hire_date)/365 > 5; |
Practice 18
编写一条SQL查询语句,显示employee的ID,last name和第一份薪水的日期
1 2 |
SELECT employee_id, last_name, hire_date, LAST_DAY(hire_date) FROM employees; |
Practice 19
编写一条SQL查询语句,显示employee的first name,雇用如期和工作经验
1 2 |
SELECT employee_id, first_name, hire_date, DATEDIFF(CURRENT_DATE(), hire_date)/365 experience FROM employees; |
Practice 20
编写一条SQL查询语句,显示department ID,年份和当年加入的employee数量
1 2 3 |
SELECT department_id, YEAR(hire_date), COUNT(employee_id) FROM employees GROUP BY department_id, YEAR(hire_date) ORDER BY department_id; |