2014-07-15 83 views
1
的最大

我的輸入文件是這樣的:蜂巢查詢來獲得計數

id,phnName,price,model 
1,iphone,2000,abc 
2,iphone,3000,abc1 
3,nokia,4000,abc2 
4,sony,5000,abc3 
5,nokia,6000,abc4 
6,iphone,7000,abc5 
7,nokia,8500,abc6 

我想寫一個蜂巢查詢來獲得特定手機的最大計數。

輸出:

iphone 3 
nokia 3 

到現在我已經試過以下查詢:

select d.phnName,count(*) from phnDetails d group by d.phnName 

,並得到輸出是這樣的:

iphone 3 
nokia 3 
sony 1 

幫我只能檢索到最大值。

+0

提供如下的回答,請讓我知道 –

回答

1

我有查詢工作

輸入

1,iphone,2000,abc 
2,iphone,3000,abc1 
3,nokia,4000,abc2 
4,sony,5000,abc3 
5,nokia,6000,abc4 
6,iphone,7000,abc5 
7,nokia,8500,abc6 

工作查詢

select c.phnName, c.counter 
from 
(select d.phnName as phnName, count(*) as counter from phnDetails d group by d.phnName) c 
join 
(select max(f.counter) as countmax from 
(select cnt.phnName as phnName, count(*) as counter from phnDetails cnt group by cnt.phnName) f) g 
where c.counter = g.countmax; 

不知道是否然而優化,它是作爲下面按預期工作

輸出, enter image description here

使用步驟如下解決,如果回答您的問題,請把它標記爲回答

CREATE TABLE phnDetails (id INT, phnName STRING, price INT, details STRING) 
ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE; 

LOAD DATA LOCAL INPATH '/home/training/Phone/phones.txt' OVERWRITE INTO TABLE phnDetails; 

select * from phnDetails; 


select d.phnName, count(*) from phnDetails d group by d.phnName; 


select c.phnName, c.counter from 
(select d.phnName as phnName, count(*) as counter from phnDetails d group by d.phnName) c ; 

select max(f.counter) as countmax from 
(select cnt.phnName as phnName, count(*) as counter from phnDetails cnt group by cnt.phnName) f ; 

select max(f.counter) as countmax from 
(select cnt.phnName as phnName, count(*) as counter from phnDetails cnt group by cnt.phnName) f ; 

select c.phnName, c.counter 
from 
(select d.phnName as phnName, count(*) as counter from phnDetails d group by d.phnName) c 
join 
(select max(f.counter) as countmax from 
(select cnt.phnName as phnName, count(*) as counter from phnDetails cnt group by cnt.phnName) f) g 
where c.counter = g.countmax; 
+0

thanks..i得到所需的輸出:) – Verify

+0

感謝您將我的解決方案標記爲已解答,您是否也可以對我的解決方案進行投票。感謝您的快速確認 –