2011-02-18 41 views
0

我有一個表'People'與這些列:id,fname,lname,addr,city,state,zip in Oracle 9.x中SQL查詢從我現有的數據表中獲取一個州中城市最多的郵政編碼

我想人口最多的郵編每個城市每個國家

我寫此查詢:

Select City, State, Zip, count(*) 
From People 
Group By City, State 
Order By count(*) 

但它給了我一個市多行對於一個國家,贊(組成): -

City -- State -- Zip -- Count(*) 
City0 -- ST0 -- 32111 -- 50 
City1 -- ST1 -- 11223 -- 100 
City1 -- ST1 -- 11225 -- 90 
City1 -- ST1 -- 11226 -- 50 
City2 -- ST1 -- 11255 -- 70 
City3 -- ST2 -- 55443 -- 60 

我試着像HAVING子句:具有計數()= MAX(計數()),但得到的錯誤消息:having子句過深或somethig嵌套(甲骨文的9.x)

我只想頂行: - City1 - ST1 - 11223 - 100 所有City1 - ST1行,其他行那裏只有一個行每個城市的每個狀態將保持不變。通緝輸出: -

City -- State -- Zip -- Count(*) 
City0 -- ST0 -- 32111 -- 50 
**City1 -- ST1 -- 11223 -- 100** 
City2 -- ST1 -- 11255 -- 70 
City3 -- ST2 -- 55443 -- 60 

我該如何做到這一點?感謝您的觀看。

==========

ANSWER FOUND吉姆·哈德森的答覆 通過修改提供的查詢一點我是正確的。最終代碼: -

select city, state, zip, counter from (
select city, state, zip, count(*) as counter from people group by city, state, zip 
) 
where counter = (
    select max(count2) from (
     select city as city1, state as state1, zip as zip1, count(*) as count2 from people group by city, state, zip ) 
    where city=city1 and state=state1 
); 
+0

如果你只通過城市和國家團體,只能選擇城市和國家(加計數) - 然後你會得到一個行每個城市/州 – 2011-02-18 17:25:54

回答

0

將您的第一個查詢視爲視圖。它給你的城市,州,郵編的計數。然後用它作爲起點。這將是容易得到最大的拉鍊人口。

例如,

select city, state, max(counter) from 
(select city, state, zip, count(*) as counter from people group by city, state, zip) 
group by city, state; 

當然,這不是很想要,因爲你想知道哪個拉鍊那是什麼。因此,舊的方式將類似於

select city, state, zip, counter from 
(select city, state, zip, count(*) as counter from people group by city, state, zip) 
where counter = (select max(count2) from (select city, state, zip, count(*) as count2 from people group by city, state, zip)); 

還有其他的方法可以做到使用分析功能的第二步。我會讓別人在這些工作。但關鍵的步驟是創建內嵌視圖,並將它作爲你進一步分析的基礎。

+0

我跑了第二個查詢,我只是得到單列返回: - 列=城市狀態的ZIP計數器|值= MEMPHIS TN 38109 1258 – 2011-02-18 21:52:26

2
select * from (
    select city, state, zip, 
    rank() over (partition by city, state order by cnt desc) rank 
    from (
    Select City, State, Zip, count(*) cnt 
    From People 
    Group By City, State, Zip 
) 
) 
where rank = 1 
+1

1這是迄今爲止而不是兩個爲其餘部分的最完美的解決方案 – jachguate 2011-02-18 22:22:29

相關問題