Home > Database > Mysql Tutorial > sql max()函数用法

sql max()函数用法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-07 17:48:58
Original
2786 people have browsed it

max看名字就知道这是求最大的值的,那么在sql中我们是读取当前数据集一个字段中最大的一值的记录,下面看max语法。

最简单的语法

SELECT MAX(expression )
FROM tables
WHERE predicates;


实例

 代码如下 复制代码

SELECT MAX(salary) as "Highest salary"
FROM employees;

让它与 GROUP BY同时使用

 代码如下 复制代码

SELECT department, MAX(salary) as "Highest salary"
FROM employees
GROUP BY department;

问:我试图拉出一个表的一些信息。为了简化,假设表(report_history)有4列:

 代码如下 复制代码

USER_NAME,report_job_id,REPORT_NAME,report_run_date。

每一份报告,是在Oracle运行时,记录写入此表,注意到上述信息。我试图做的是拉从这个表中,当最后一次每一个不同的运行报告和谁跑,最后。

我的查询:

 代码如下 复制代码

SELECT report_name, max(report_run_date)
FROM report_history
GROUP BY report_name

但这样的结果是有问题的,下面看看正确的做法

 代码如下 复制代码

SELECT rh.user_name, rh.report_name, rh.report_run_date
FROM report_history rh,
   (SELECT max(report_run_date) as maxdate, report_name
     FROM report_history
     GROUP BY report_name) maxresults
WHERE rh.report_name = maxresults.report_name
AND rh.report_run_date= maxresults.maxdate;

Let's take a few moments to explain what we've done.

方法二

 代码如下 复制代码

   (SELECT max(report_run_date) as maxdate, report_name
     FROM report_history
     GROUP BY report_name) maxresults

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template