Home  >  Article  >  Database  >  sql分组取最大记录方法

sql分组取最大记录方法

WBOY
WBOYOriginal
2016-06-07 17:51:302211browse

要想取利用group by 分组后第一条记录我们就需要结合order by 来操作,原是是很利用group by 把所有分组取出来,然后来利用order by 对分组里面的数据进行desc排序取第一条就KO了。

先看看group by 语句的用法


GROUP BY 语句
GROUP BY 语句用于结合合计函数,根据一个或多个列对结果集进行分组。

 点击可查看源文

 代码如下 复制代码

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name


在SQL的 语句一起使用同样数目的SQL聚合函数提供分组的某些教程表列(第结果数据集方法)。


实例

以下是 test 表,测试sql

 

 代码如下 复制代码

CREATE TABLE IF NOT EXISTS `test` (
`id` int(10) unsigned NOT NULL auto_increment,
`install` int(10) unsigned NOT NULL,
`day` int(10) unsigned NOT NULL,
`aid` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;


INSERT INTO `test` (`id`, `install`, `day`, `aid`) VALUES
(1, 'www.111cn.net', 20120308, 1),
(2, 2321, 20120309, 2),
(3, 1236, 20120310, 3),
(5, 'www.hzhuti.com', 20120309, 1),
(6, 2312, 20120310, 1),
(7, 1432, 20120311, 1),
(8, 2421, 20120308, 2),
(9, 4245, 20120311, 2),
(10, 'www.111cn.net', 20120310, 2),
(11, 412, 20120308, 3);

实现sql语句

 代码如下 复制代码

SELECT A.* FROM test A,
(SELECT aid, MAX(day) max_day FROM test GROUP BY aid) B
WHERE A.aid = B.aid AND A.day = B.max_day
ORDER BY a.install DESC

这样我们只要取集合的还desc排序的第一条就可以了。


再看个mssql server实例

 

例如 table1(a,b,c,d)

 代码如下 复制代码

a    b    c    d
1    0    c1  d1
1    1    c2  d2
1    3    c3  d3

4    0    c4  d4

5     1   c5   d5
5     2   c6   d6

6     1   c7   d7
6     4   c8   d8

我要得到的是按a分组,在每个分组中取b值最大的一条记录,就是

 代码如下 复制代码
a   b   c   d
1   3   c3   d3
4   0   c4   d4
5   2   c6   d6
6   4   c8   d8

方法一

 代码如下 复制代码

* from table1 where b in (select max(b) from table1 group by a) ;

方法二

 代码如下 复制代码

select * from table1 a where b=(select max(b) from table1 where a=a.a)


好了就讲这么多了,希望对大家有用。

Statement:
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