2011-09-01 82 views
2

下面是表: 用戶如何編寫這條SQL語句?

Name: Subject: 
Peter Math 
Mary Chinese 
Mary Computer 
Mary Hist 
Mary PE 
Mary English 
Peter Art 
Chris English 
Chris Computer 
Peter Computer 
Paul Math 

我想獲得的頂部出現在名稱,並返回前4的結果應該是主題名稱。例如,在這種情況下,頂部出現的名字是瑪麗,並在主題的順序基地,中國,計算機,英語,所以我想有結果:

Mary Chinese 
Mary Computer 
Mary English 
Mary Hist 

如果瑪麗是不是最足顯示結果,第二人會後續一樣,讓說,該表將是這樣的:

Name: Subject: 
Peter Math 
Mary Chinese 
Mary Computer 
Mary Hist 
Peter Art 
Chris English 
Chris Computer 
Peter Computer 
Paul Math 

其結果將是,

Mary Chinese 
Mary Computer 
Mary Hist 
Peter Art 

因爲瑪麗是最出現,所以瑪麗會回來,布瑪麗是不足以填補4個職位,所以第二個出現將佔據位置,在這種情況下,我們使用彼得。

+0

@Martin,yes請注意'peter'和'chris'並列第二名。 – Johan

回答

5
 
SELECT user.name, user.subject 
FROM user 
INNER JOIN (
    SELECT name, COUNT(1) AS occurrences 
    FROM user 
    GROUP BY name 
) AS user_occurrences 
    ON user.name = user_occurrences.name 
ORDER BY user_occurrences.occurrences DESC, user.name ASC, user.subject ASC 
LIMIT 4 

編輯這可能會表現得更好,這取決於您使用的RDBMS和數據集的大小。嘗試兩者並進行比較。

 
SELECT user.name, user.subject 
FROM user 
INNER JOIN user AS user_occurrences 
    ON user.name = user_occurrences.name 
GROUP BY user.name --, user.subject Second GROUP BY not needed on MySQL, but it should logically be there 
ORDER BY COUNT(user_occurrences.subject) DESC, user.name ASC, user.subject ASC 
LIMIT 4 
+0

,,很長時間..... – DNB5brims

+0

嗯......我現在還不確定:PI認爲我誤讀了一些東西......讓我檢查 – shesek

+0

你是對的,編輯(指向似乎刪除了他的評論的人?) – shesek

1

按名稱從組中選擇前4,主題和排序算

MSSQL代碼:

select top 4 q.marketname, cc.countryname from (
select top 100 m.MarketName, m.MarketId, COUNT(m.marketname) as [count] 
from Common.Country c inner join Common.Market m on c.MarketId = m.MarketId 
group by m.MarketName, m.MarketId order by COUNT(m.marketname) desc) 
q inner join Common.Country cc 
on cc.MarketId = q.MarketId order by [Count] desc 

也可以做類似MySQL的代碼

這裏是培訓相關MySQL代碼

select q.name, cc.subject from (
    select m.Name, count(*) as Count 
    from User m 
    group by m.Name 
    order by COUNT(*) desc 
    LIMIT 100 
) q 
inner join user cc on cc.Name= q.name 
order by Count desc 
LIMIT 4 

這是很受歡迎的,你想要不費吹灰之力?你不能在你的技術中實現邏輯嗎?如果沒有理解解決方案建議,你不應該倒退。

+0

-1,這是SQL服務器語法,不適用於MySQL。 – Johan

+0

@johan,這不是語法。這個僞代碼 – hungryMind

+0

作爲僞代碼它也不起作用。按名稱,主題分組是錯誤的。它需要一個名稱組,然後例如一個連接,儘管可能有更有效的方法。 –