如何查找表的顶部或最大列值?

时间:2018-08-27 07:43:16

标签: sql oracle greatest-n-per-group

具有下表,该表是某种http请求日志:

+---------+----------+-----------+----------+
| County  |  Mobile  |    OS     | Browser  |
+---------+----------+-----------+----------+
| USA     | iPhone   | iOS       | Safar    |
| UK      | Samsung  | Android   | Chrome   |
| India   | Motorola | Android   | Chrome   |
| India   | Nokia    | Android   | Chrome   |
| Russia  | Nokia    | Microsoft | Edge     |
| Germany | Sony     | Android   | Chrome   |
| India   | Sony     | Android   | Chrome   |
| Russia  | Nokia    | Microsoft | Edge     |
| Germany | Sony     | Android   | Chrome   |
| India   | Motorola | Android   | Chrome   |
| Russia  | Nokia    | Android   | Edge     |
| Germany | Sony     | Android   | Chrome   |
+---------+----------+-----------+----------+

如何找到每个县使用最多的手机,操作系统和浏览器,并得到类似

的结果
+---------+----------+-----------+----------+
| County  |  Mobile  |    OS     | Browser  |
+---------+----------+-----------+----------+
| USA     | iPhone   | iOS       | Safar    |
| UK      | Samsung  | Android   | Chrome   |
| India   | Motorola | Android   | Chrome   |
| Russia  | Nokia    | Microsoft | Edge     |
| Germany | Sony     | Android   | Chrome   |
+---------+----------+-----------+----------+ 

因此,美国最常用的手机是iPhone,最常用的操作系统是iO,最常用的浏览器是Safar,依此类推...

2 个答案:

答案 0 :(得分:2)

如果您的DBMS支持窗口功能,可以尝试一下。

尝试使用CTE写子查询通过COUNTCountyMobileOS列数获取Browser并使用{{1 }}通过row_number来创建行号,然后得到cnt

rn=1

查询1

CREATE TABLE T(
   County VARCHAR(50),
     Mobile VARCHAR(50),
     OS VARCHAR(50),
     Browser VARCHAR(50)
);


INSERT INTO T VALUES ('USA','iPhone', 'iOS', 'Safar');
INSERT INTO T VALUES ('UK','Samsung', 'Android' , 'Chrome');
INSERT INTO T VALUES ('India','Motorola','Android' , 'Chrome');
INSERT INTO T VALUES ('India','Nokia','Android', 'Chrome');
INSERT INTO T VALUES ('Russia','Nokia','Microsoft', 'Edge');
INSERT INTO T VALUES ('Germany','Sony','Android','Chrome');
INSERT INTO T VALUES ('India','Sony','Android','Chrome');
INSERT INTO T VALUES ('Russia','Nokia','Microsoft','Edge');
INSERT INTO T VALUES ('Germany','Sony','Android','Chrome');
INSERT INTO T VALUES ('India','Motorola','Android','Chrome');
INSERT INTO T VALUES ('Russia','Nokia','Android','Edge');
INSERT INTO T VALUES ('Germany','Sony','Android','Chrome');

Results

with cte as (
  select County,Mobile,OS,Browser,COUNT(*) cnt
  from T
  GROUP BY County,Mobile,OS,Browser
)
SELECT 
    t1.County,
    t1.Mobile,
    t1.OS,
    t1.Browser 
FROM (
  select t1.*,row_number() over(partition by County order by cnt desc) rn
  from cte t1
) t1
where t1.rn = 1
ORDER BY COUNTY desc

答案 1 :(得分:0)

尝试一下:它将在oracle中工作

select * from 
(select max(rn) rn1 ,country
from
(
select *, row_number over partition by (Mobile, OS,Browser order by County) as rn
from tablename)a)x inner join 
(
select *, row_number over partition by (Mobile, OS,Browser order by County) as rn
from tablename)b on b.rn=x.rn1 and b.country=x.country