1. 程式人生 > >sql根據多字段分組並查詢每組內top1

sql根據多字段分組並查詢每組內top1

輸出 origin style rom bsp art tab any sele

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