sql根据多字段分组并查询每组内top1

Posted mu_fire

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql根据多字段分组并查询每组内top1相关的知识,希望对你有一定的参考价值。

 

1.如下表格,查询2017年Q1季度的从a_country发往其他城市的货量最高的公司,并输出货量总和

id
from_country
to_country
company_name
company_count
year
quarter
month
               
SELECT  * FROM(

	SELECT  sum(company_count) as top_count,company_name
	FROM testData
	WHERE `year`=‘2017‘ AND `quarter`=‘Q1‘ AND from_country=‘a_country‘
	GROUP BY from_country,to_country,company_name,`year`,`quarter`
	ORDER BY company_count DESC) AS A

GROUP BY from_country,to_country

2.条件同1,同时查询公司b

SELECT * FROM

	(SELECT  * FROM(

		SELECT  sum(company_count) as top_count,company_name,company_count
		FROM testData
		WHERE `year`=‘2017‘ AND `quarter`=‘Q1‘ 
		GROUP BY from_country,to_country,company_name,`year`,`quarter`
		ORDER BY company_count DESC) AS A

	GROUP BY from_country,to_country) AS TopCompany

	INNER JOIN

	(SELECT  B_count,to_country FROM(

		SELECT  sum(company_count) as B_count,company_name as B,to_country
		FROM testData
		WHERE `year`=‘2017‘ AND `quarter`=‘Q1‘  AND company_name=‘B‘
		GROUP BY from_country,to_country,company_name,`year`,`quarter`
		ORDER BY company_count DESC) AS Bdata

	GROUP BY origin_country_name,dest_country_name) AS BCompany

ON TopCompany.to_country =BCompany.to_country 

  

 

以上是关于sql根据多字段分组并查询每组内top1的主要内容,如果未能解决你的问题,请参考以下文章

分组后取每组内排名的Top N的SQL语句

mysql 分组子查询sql怎么写

sql 分组排序

sql中如何查看某一字段值有几个数值

SQL查同一个字段输出两列?

mysql分组排序后取出几条记录,