2012-05-11 212 views
1

我已簡化了我的問題並創建了此示例以更好地說明。sql。獲得最大值(平均值(列))

我的表:

CREATE TABLE `table_company` (
    `source_id` INT(10) UNSIGNED NOT NULL, 
    `company_id` INT(10) UNSIGNED NOT NULL, 
    `clicks` INT(10) UNSIGNED NOT NULL, 
    PRIMARY KEY (`source_id`,`company_id`) 
) ENGINE=INNODB DEFAULT CHARSET=utf8; 

我的數據:

INSERT INTO table_company VALUES 
(1,100,8),(2,100,7),(3,200,9),(4,300,3),(5,100,4),(6,400,5),(7,100,10),(8,500,4),(9,500,9),(10,400,9); 


SELECT source_id,company_id,AVG(clicks) AS avg_click FROM table_company 
GROUP BY source_id,company_id 
ORDER BY avg_click DESC; 

給我:

source_id company_id avg_click 
--------- ---------- ----------- 
     7   100  10.0000 
     3   200  9.0000 
     9   500  9.0000 
     10   400  9.0000 
     1   100  8.0000 
     2   100  7.0000 
     6   400  5.0000 
     5   100  4.0000 
     8   500  4.0000 
     4   300  3.0000 

我想編寫一個查詢給我:

source_id company_id avg_click 
--------- ---------- ----------- 
     7   100  10.0000 
     3   200  9.0000 
     9   500  9.0000 
     10   400  9.0000 
     4   300  3.0000 

即。只有保持這種有MAX(avg_click)的COMPANY_ID

回答

4
SELECT source_id, company_id, MAX(avg_click) as max_click FROM 
(SELECT source_id,company_id,AVG(clicks) AS avg_click FROM table_company 
GROUP BY source_id,company_id 
ORDER BY avg_click DESC) tmp 
GROUP BY company_id 
+0

感謝。我有類似的東西,但沒有正確執行我的外部GROUP BY。 – Yada

0
SELECT MAx(source_id), company_id, MAX(avg_click) 
from (SELECT source_id,company_id,AVG(clicks) AS avg_click FROM #table_company 
    GROUP BY source_id,company_id 
    )as tbl 
GROUP by company_id 
0

你可以使用相關:

SELECT source_id, company_id, avg_click 
FROM table_company TC 
WHERE avg_click=(SELECT max(avg_click) 
      FROM table_company TC2 
      WHERE TC.company_id=TC2.company_id 
      GROUP BY TC2.company_id); 

您也可以使用WITH子句:

WITH pom AS(SELECT company_id, max(avg_click) MaxAvgCl 
      from table_company 
      group by company_id) 
SELECT pom.company_id, T.avg_click, T.source_id 
FROM pom JOIN table_company T on T.company_id=pom.company_id 
           and T.avg_click=pom.MaxAvgCl; 
相關問題