码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2018-08-25 16:33:11      阅读:541      评论:0      收藏:0      [点我收藏+]

标签:sel   div   tab   查询   2017年   uart   try   select   any   

 

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

标签:sel   div   tab   查询   2017年   uart   try   select   any   

原文地址:https://www.cnblogs.com/mufire/p/9534226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!